-
第一种方法,使用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://img-blog.csdnimg.cn/img_convert/ddb4605785475eaf341a1e5da65283a9.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://img-blog.csdnimg.cn/img_convert/aed92f0b6a3aa6011cfc226d35dc9035.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://img-blog.csdnimg.cn/img_convert/6f86f005b7ba26e5c8854201e387a950.png)