[英]Thread creation by extending Thread class
这是一个有关通过扩展Thread
类创建线程的简单示例。
class Count extends Thread {
Count() {
super("my extending thread");
System.out.println("my new thread is started " + this);
start();
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println("count " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("my thread run is over");
}
}
}
public class Multi2 {
public static void main(String[] args) {
Count c = new Count();
try {
while (c.isAlive()) {
System.out.println("main thread is alive untill child thread is alive");
Thread.sleep(1500);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("main thread is over");
}
}
}
我的输出就是这个。
my new thread is started Thread[my extending thread,5,main]
main thread is alive untill child thread is alive
count 0
count 1
main thread is alive untill child thread is alive
count 2
main thread is alive untill child thread is alive
count 3
count 4
main thread is alive untill child thread is alive
count 5
main thread is alive untill child thread is alive
count 6
count 7
main thread is alive untill child thread is alive
count 8
main thread is alive untill child thread is alive
count 9
my thread run is over
main thread is over
我的问题是
01. main thread is alive untill child thread is alive
如何main thread is alive untill child thread is alive
之前输出
count 0 count 1
02.在main thread is alive untill child thread is alive
输出之前, main thread is alive untill child thread is alive
保持main thread is alive untill child thread is alive
并与run()
方法的输出一起继续打印?
请帮我解决这个问题。
谢谢。
Count有这一行:
Thread.sleep(1000);
您的主程序有这一行:
Thread.sleep(1500);
显然,您将获得每3个计数打印2个主要打印。 这就是0和1彼此相邻的原因。
至于为什么要在计数打印之前看到主打印,您可以看到以下内容:
Count c = new Count();
try {
while (c.isAlive()) {
System.out.println("main thread is alive untill child thread is alive");
Thread.sleep(1500);
您已经关闭了c
但是直到JVM执行上下文切换以实际运行该线程之前,您可能看不到结果。 事实是,在某些系统上,您可能会在此之前查看计数器。 通常,因为它离开始时还很近并且还没有屈服,所以您会在柜台前看到主要印刷品。
对于第二部分,您的main thread is...
继续打印,因为它有一个循环,告诉您要进行打印直到计数器线程不再存在为止。 它们都使用System.out
因此当您查看控制台时,都可以在其中看到它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.