线程间通信Thread.join
在很多应用场景中存在这样一种情况,主线程创建并启动子线程后,如果子线程要进行很耗时的计算,那么主线程将比子线程先结束,但是主线程需要子线程的计算的结果来进行自己下一步的计算,这时主线程就需要等待子线程,java中提供可join()方法解决这个问题。
join()方法的作用,是等待这个线程结束;
也就是说,t.join()方法阻塞调用此方法的线程(calling thread)进入 TIMED_WAITING 状态,直到线程t完成,此线程再继续;
通常用于在main()主线程内,等待其它线程完成再结束main()主线程
package com.dongguo.sync;
/** * @author Dongguo * @date 2021/8/23 0023-23:01 * @description: join */
public class ThreadDemo4 {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "开始执行");
Thread threadA = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "开始执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行结束");
}, "ThreadA");
Thread threadB = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "开始执行");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行结束");
}, "ThreadB");
try {
threadA.start();
threadA.join();
threadB.start();
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行结束");
}
}
运行结果:
main开始执行
ThreadA开始执行
ThreadA执行结束
ThreadB开始执行
ThreadB执行结束
main执行结束
每个线程的终止的前提是前驱线程的终止,每个线程等待前驱线程终止后,才从join方法返回,实际上,这里涉及了等待/通知机制,即下一个线程的执行需要接受前驱线程结束的通知。
还没有评论,来说两句吧...