我正在尝试Java 8并发的第一步。 在下面的代码示例中,抛出异常,因为我的任务睡眠时间为2秒。关闭功能等待5秒钟终止。因此,只执行两个循环。有没有动态解决方案,而不是计算执行可能采取的最大时间和调整awaitTermination() - 方法的值?
public class Application {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(1);
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);
}
})
);
shutdown(executor);
}
private static void shutdown(ExecutorService executor) {
try {
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.err.println("tasks interrupted");
} finally {
if (!executor.isTerminated()) {
System.err.println("cancel non-finished tasks");
}
executor.shutdownNow();
}
}
答案 0 :(得分:5)
添加@AdamSkyWalker提到的内容,您可以使用CountDownLatch,因为您已经知道了线程的数量(在这种情况下为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();
}
}
我在比较CountDownLatch
,Semaphore
和CyclicBarrier
的某个时候写了post,这对您有所帮助。