我正在使用ExecutorCompletionService提交幾個任務。然後我想等待最長時間,例如5秒,然後停止處理。ExecutorCompletionService等待最多n秒完成
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'? – SpiderPig
btw。期貨也有'取消'的方法。 – SpiderPig