在某些情况下,主线程创建并启动了子线程,如果子线程中需要进行大量的耗时运算,主线程往往将早于子线程结束之前结束,如果主线程想等待子线程执行完毕后,获得子线程中的处理完的某个数据,就要用到join方法了。
public class Join {
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new MyThread("t1"));
t1.start();
t1.join();
for (int i = 0; i < 10; i++) {
System.out.println("我是主线程");
}
}
}
class MyThread implements Runnable{
private String name;
public MyThread(String name){
this.name = name;
}
@Override
public void run() {
try {
Thread.sleep(3000);
for (int i = 0; i < 10; i++) {
System.out.println(name + "子线程运行 " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
执行结果:
t1子线程运行 0
t1子线程运行 1
t1子线程运行 2
t1子线程运行 3
t1子线程运行 4
t1子线程运行 5
t1子线程运行 6
t1子线程运行 7
t1子线程运行 8
t1子线程运行 9
我是主线程
我是主线程
我是主线程
我是主线程
我是主线程
我是主线程
我是主线程
我是主线程
我是主线程
我是主线程
join使得线程执行能够按照既定的顺序执行,比如 t2在t1执行完以后再执行