-
第一种方法,使用CompletableFuture的join方法
public static void test1() {
ThreadPoolExecutor executorService = new ThreadPoolExecutor(10, 100, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), new DefaultManagedAwareThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
List<CompletableFuture<Void>> completableFutures = new ArrayList<>();
for (int i = 0; i < 4; i++) {
int finalI = i;
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
log.info(Thread.currentThread().getName()+"==>"+finalI);
}, executorService);
completableFutures.add(completableFuture);
}
for (CompletableFuture<Void> completableFuture : completableFutures) {
completableFuture.join();
}
log.info(Thread.currentThread().getName()+"==>"+"finish");
}
结果
![](https://i-blog.csdnimg.cn/blog_migrate/e402f3bdc945009566df84078b73c8c1.png)
-
第二种方法,使用CountDownLatch
private static void test2() throws InterruptedException {
ThreadPoolExecutor executorService = new ThreadPoolExecutor(10, 100, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), new DefaultManagedAwareThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
CountDownLatch countDownLatch = new CountDownLatch(4);
for (int i = 0; i < 4; i++) {
int finalI = i;
executorService.execute(() -> {
try {
Thread.sleep(1000);
log.info(Thread.currentThread().getName()+"==>"+finalI);
} catch (Exception e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
});
}
countDownLatch.await(10, TimeUnit.SECONDS);
log.info(Thread.currentThread().getName()+"==>"+"finish");
}
结果
![](https://i-blog.csdnimg.cn/blog_migrate/b9f48e49674189cf83c675f46f36fc66.png)
-
第三种方法,使用CyclicBarrier
和CountDownLatch不同的是CyclicBarrier是线程间的相互等待,而CountDownLatch是多个或一个线程等待线程,CyclicBarrier是可以复用的。在CyclicBarrier的构造函数中,参数需要小于等于await方法的调用次数,只有当await到达一定的次数,才会放行主线程继续执行。
private static void test3() throws Exception{
CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
ThreadPoolExecutor executorService = new ThreadPoolExecutor(10, 100, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), new DefaultManagedAwareThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 4; i++) {
int finalI = i;
executorService.execute(() -> {
try {
Thread.sleep(1000);
log.info(Thread.currentThread().getName() + "==>" + finalI);
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
});
}
cyclicBarrier.await();
log.info(Thread.currentThread().getName() + "==>" + "finish");
}
结果
![](https://i-blog.csdnimg.cn/blog_migrate/36ef0e751159806d5d91ceb4e23a55ad.png)