【发布时间】:2015-09-27 05:19:09
【问题描述】:
我正在使用 ExecutorCompletionService 提交一些任务。然后我想等待最大值,比如 5 秒,然后停止处理。
ExecutorService executorService = Executors.newFixedThreadPool(10);
CompletionService<String> completionService = new ExecutorCompletionService<String>(
executorService);
List<Callable<String>> callables = createCallables(); //each callable sleeps randomly between 1-10 seconds and then prints the thread name
for (Callable<String> callable : callables)
taskCompletionService.submit(callable);
for (int i = 0; i < callables.size(); i++) {
Future<String> result = completionService.take();
System.out.println(result.get());
}
现在我不想等待超过 5 秒来完成所有任务。我只想收集在 5 秒内完成的任务的结果。我怎样才能做到这一点?
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
我在executorService 上使用了shutdown 和awaitTermination,但我的主线程仍在等待所有提交的任务完成,所有任务完成需要10 秒并打印每个线程的名称。如何在 5 秒内停止处理?
【问题讨论】:
-
你试过
awaitTermination然后shutdownNow吗? -
顺便说一句。 futures 也有一个
cancel方法。
标签: java multithreading concurrency executorservice java-threads