这样做有什么错吗?我目前正在学习线程
thread1.start();
thread1.join();
thread2.start();
thread2.join();编辑:我知道这是一个错误,因为它在我学习的源码中。然而,来源并没有提供为什么它是错误的答案
在线程上使用和不使用.join有什么区别?
发布于 2014-12-03 05:56:02
没有理由启动新的线程,然后立即加入它。join()将暂停当前线程,直到其他线程完成。这将具有与写入相同的效果:
thread1.run();
thread2.run();作者的意思可能是:
thread1.start();
thread2.start();
thread1.join();
thread2.join();这样,thread1和thread2就可以同时执行。
发布于 2014-12-03 05:56:29
如果你把它放在try/catch中,它不是一个错误,但会有一个问题,为什么你要这样做并使用线程?这将等到thread1死后再开始使用thread2。这个来自here的示例将有助于您理解join()的概念(请阅读他们解释得非常好的评论):
t1.start();
//start second thread after waiting for 2 seconds or if it's dead
try {
t1.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
//start third thread only when first thread is dead
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t3.start();
//let all threads finish execution before finishing main thread
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}发布于 2014-12-03 06:03:33
很难判断这是不是一个错误。这取决于您在线程thread1和thread2中所做的工作,以及您试图实现的目标。
来自Java文档:
thread1.join();使当前线程暂停执行,直到线程1的线程终止。
如果您试图同时启动两个线程,那么这将是一个问题,因为线程将被连续启动。
https://stackoverflow.com/questions/27259627
复制相似问题