join用法

为什么需要 join

下面的代码执行,打印 r 是什么?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
static int r = 0;
public static void main(String[] args) throws InterruptedException {
test1();
}
private static void test1() throws InterruptedException {
log.debug("开始");
Thread t1 = new Thread(() -> {
log.debug("开始");
sleep(1);
log.debug("结束");
r = 10;
});
t1.start();
log.debug("结果为:{}", r);
log.debug("结束");
}

分析

  • 因为主线程和线程 t1 是并行执行的,t1 线程需要 1 秒之后才能算出 r=10

  • 而主线程一开始就要打印 r 的结果,所以只能打印出 r=0

解决方法

  • 用 join,加在 t1.start() 之后即可

哪个线程对象调用join,就等待哪个线程运行结束

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
static int r = 0;
public static void main(String[] args) throws InterruptedException {
test1();
}
private static void test1() throws InterruptedException {
log.debug("开始");
Thread t1 = new Thread(() -> {
log.debug("开始");
sleep(1);
log.debug("结束");
r = 10;
});
t1.start();
t1.join();
log.debug("结果为:{}", r);
log.debug("结束");
}

t1.join()加在 t1.start() 之后,表示主线程等待t1线程运行结束