【发布时间】:2016-12-28 06:29:55
【问题描述】:
我有这个java main 方法
public class ThreadJoinExample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
TestJoinClass t1 = new TestJoinClass("t1");
TestJoinClass t2 = new TestJoinClass("t2");
TestJoinClass t3 = new TestJoinClass("t3");
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
//thread 3 won't start until thread 2 is complete
t3.start();
}
}
我的线程类是
public class TestJoinClass extends Thread{
//Constructor to assign a user defined name to the thread
public TestJoinClass(String name)
{
super(name);
}
public void run(){
for(int i=1;i<=5;i++){
try{
//stop the thread for 1/2 second
Thread.sleep(500);
}
catch(Exception e){System.out.println(e);}
System.out.println(Thread.currentThread().getName()+
" i = "+i);
}
}
}
这个程序的输出是
t1 i = 1
t1 i = 2
t1 i = 3
t1 i = 4
t1 i = 5
t3 i = 1
t2 i = 1
t3 i = 2
t2 i = 2
t3 i = 3
t2 i = 3
t3 i = 4
t2 i = 4
t3 i = 5
t2 i = 5
我有一个小问题。我想知道为什么 t3 首先开始运行而不是 t2?在代码中,它显示 t2.start() 先于 t3.start() 执行。输出不应该显示 t2 在 t3 之前先执行吗?谢谢
【问题讨论】:
-
//线程 3 在线程 2 完成之前不会启动 不正确
-
t2 t3 将并行运行,因此结果将是随机的
-
Java Thread Example?的可能重复
-
线程 t2 和 t3 是异步线程。无法确定谁先完成。
-
寓意是,在使用线程时,如果您希望事情以特定的顺序发生,您需要添加自己的同步代码,以便您的所有线程可以协调它们的活动。
标签: java