除了@AdamSkyWalker提到的之外,您还可以使用CountdownClast,因为您已经知道线程数(本例中为10个)。
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
final CountDownLatch latch = new CountDownLatch(10);
IntStream.range(0, 10).forEach(i ->
executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("Hello");
} catch (InterruptedException e) {
throw new IllegalStateException("Task interrupted", e);
} finally {
latch.countDown();
}
})
);
latch.await();
}
}
我写了一个
post
回头再比较一下
CountDownLatch
,
Semaphore
和
CyclicBarrier
这对你很有帮助。