我正在尝试Java 8并发的第一步。在下面的代码示例中,因为my tasks休眠2秒而引发异常。关机功能等待5秒后终止。因此,只执行两个循环。有没有动态的解决方案,而不是计算执行所需的最大时间并调整awaitTermination()-method的值?
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();
}
}发布于 2018-02-19 18:19:00
除了@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,它会对你有帮助。
https://stackoverflow.com/questions/48863715
复制相似问题