先来假设这么一个场景:
@Slf4j
public class TestJoin {
private static int num = 0;
public static void main(String[] args) {
new Thread(){
@Override
public void run(){
log.info("start sleeping...");
try {
Thread.sleep(1000);
num = 10;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
log.info("value of num:{}",num);
}
}
num的值会输出什么?0还是10?因为休眠了1s,应该会输出0。也就是说,线程还没给num赋值,主线程已经要获取num的值了。 也就是说,join的使用场景是一个线程需要等待另一个线程执行完后再继续执行。
@Slf4j
public class TestJoin {
private static int num = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(){
@Override
public void run(){
log.info("start sleeping...");
try {
Thread.sleep(1000);
num = 10;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
t1.join();
log.info("value of num:{}",num);
}
}
使用join()方法之后就可以等待线程t1执行完成,得到预期的结果。