Thread 中的 join() 方法的作用是调用线程等待该线程运行完后,再继续运行
例子:
//
public class JoinTest {
//
public static void main(String[] a){
System.out.println("main thread start");
Thread t1 = new Thread(new Worker("worker-1"));
Thread t2 = new Thread(new Worker("worker-2"));
t1.start();
t2.start();
// 注意,要在 t1、t2 都启动后,再运行 t1、t2 的 join
try{
t1.join();
}catch(InterruptedException e){
e.printStackTrace();
}
try{
t2.join();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("main thread end");
}
}
class Worker implements Runnable{
private String name;
public Worker(String name){
this.name = name;
}
//
public void run(){
for(int i = 0; i < 5; i++){
try {
Thread.sleep(1L);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(name);
}
}
}
参考: blog.youkuaiyun.com/wangshuminjava/article/details/86698916
本文深入探讨了Java中Thread类的join()方法,通过具体示例解释了如何使用join()确保主线程等待子线程完成。理解join()对于同步线程执行顺序至关重要。
7066

被折叠的 条评论
为什么被折叠?



