Java多线程--让主线程等待子线程执行完毕
使用Java多线程编程时经常遇到主线程需要等待子线程执行完成以后才能继续执行,那么接下来介绍一种简单的方式使主线程等待。
java.util.concurrent.CountDownLatch
使用countDownLatch.await()方法非常简单的完成主线程的等待:
public class ThreadWait {
public static void main(String[] args) throws InterruptedException {
int threadNumber = 10;
final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);
for (int i = 0; i < threadNumber; i++) {
final int threadID = i;
new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("threadID:[%s] finished!!", threadID));
countDownLatch.countDown();
}
}.start();
}
countDownLatch.await();
System.out.println("main thread finished!!");
}
} 相关推荐
ErixHao 2020-05-30
ALiDan 2020-04-16
王道革 2020-04-11
sunzxh 2020-03-23
付春杰Blog 2020-02-17
spb 2020-02-01
xzkjgw 2020-01-17
abdstime 2020-01-17
Cheetahcubs 2020-01-04
zhujiangtaotaise 2019-12-26
zhangxiaocc 2019-11-07
Wisher 2017-06-07
思捻如枫 2019-07-01
leys 2019-07-01
讨厌什么变成什么 2019-06-30
浪里xiao白龙 2019-06-28
mojianc 2019-06-28
liwenbocsu 2019-06-28
了缺 2019-06-28