看看join 阻塞
很多时候,一个线程的输入可能非常依赖于另外一个或者多个线程的输出,此时,这个线程就需要等待依赖的线程执行完毕,才能继续执行。jdk提供了join()操作来实现这个功能
A依赖B,那么在A线程中去调用 B.join() ,A线程开始等待B线程
无限等待,直到目标线程执行完毕
public final void join() throws InterruptedException;
在给定的时间,B线程没有执行完成,那么A线程就不等了,开始执行,(cpu调度获得执行权)
public final synchronized void join(long millis) throws InterruptedException;
看个案例
package juc;
/**
* @author yanjun.liu
* @date 2020/6/20--13:27
*/
public class MyThread {
/**
* t1线程,对num++,主线程等待t1执行完成,主线程进行打印num
*/
static int num = 0;
public static class T1 extends Thread {
public T1(String name) {
super(name);
}
@Override
public void run() {
System.out.println(System.currentTimeMillis() + ",start " + this.getName());
for (int i = 0; i < 10; i++) {
num++;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(System.currentTimeMillis() + ",end " + this.getName());
}
}
public static void main(String[] args) throws InterruptedException {
//创建线程
T1 t1 = new T1("t1");
//调用start准备执行,等待cpu调度
t1.start();
//main线程进行等待t1线程执行完毕
//(main线程需要t1线程执行的结果,那么main线程必须等待t1执行完成,就需要由main线程去调用t1线程的join方法)
t1.join();
System.out.println(System.currentTimeMillis() + ",num = " + num);
}
}