为什么需要 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("结束"); }
|
分析
解决方法
- 用 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线程运行结束