标签:线程阻塞 throws await 对象 否则 简单 bsp countdown 辅助
测试代码如下:
public class ThreadWait {
public static void main(String[] args) throws InterruptedException {
ExecutorService exector = Executors.newFixedThreadPool(5);
int threadNumber = 13;
final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);
for (int i = 0; i < threadNumber; i++) {
final int threadID = i;
exector.execute(
() -> {
try {
Thread.sleep(2000);
System.out.println(String.format("threadID:[%s] finished!!", threadID));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown(); //这个不管是否异常都需要数量减,否则会被堵塞无法结束
}
}
);
}
countDownLatch.await();//保证之前的所有的线程都执行完成,才会走下面的
System.out.println(countDownLatch.getCount());
System.out.println("main thread finished!!");
}
}
结果为:
threadID:[0]finished!!
threadID:[1]finished!!
threadID:[4]finished!!
threadID:[3]finished!!
threadID:[2]finished!!
threadID:[9]finished!!
threadID:[8]finished!!
threadID:[5]finished!!
threadID:[6]finished!!
threadID:[7]finished!!
threadID:[10]finished!!
threadID:[11]finished!!
threadID:[12]finished!!
0
main thread finished!!
标签:线程阻塞 throws await 对象 否则 简单 bsp countdown 辅助
原文地址:https://www.cnblogs.com/-flq/p/14867493.html