![](/img/trans.png)
[英]How to stop executor service threads even when their task is not completed?
[英]How to get the completed task on Executor Service till some time?
我想檢索已完成任務的線程的結果並檢索結果並忽略其他線程。 我的目標是做這樣的事情。
public class Main {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(16);
for(int i = 0 ; i < 100 ; i++) {
service.submit(threadClass);
// some thread that generates result in 5 seconds say
}
// Main thread does some work here that takes time
/*
The task that has finished till this point should be taken
Let's say 7 results are generated till this point,
So get the 7 results and stop other threads
Want result like a List<Integer>
*/
service.shutdownNow(); // stop all other threads
}
}
您可以使用CompletionService ,內部使用阻塞隊列,“已完成”的Future
將放入此隊列,因此您可以調用queue#poll
來獲取所有完成Future
。 :
ExecutorService service = Executors.newFixedThreadPool(16);
CompletionService<Integer> completionService = new ExecutorCompletionService<>(service);
for(int i = 0 ; i < 100 ; i++) {
completionService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Random random = new Random();
int nextInt = random.nextInt(10000);
System.out.println("I will take " + nextInt + " ms to finish");
try {
Thread.sleep(nextInt);
} catch (InterruptedException e) {
System.out.println("I am interrupt");
return -1;
}
System.out.println("I am finish");
return nextInt;
}
});
}
// do other work
Thread.sleep(5000);
List<Integer> completeResult = new ArrayList<>();
Future<Integer> future;
while ((future = completionService.poll()) != null) {
try {
completeResult.add(future.get());
} catch (Exception exception) {
// exception
}
}
service.shutdownNow();
System.out.println(completeResult);
ExecutorService.submit
返回一個Future
,可以用來等待完成並get
結果。
有一個版本的get
有超時,這對於輪詢完成很有用。
您應該收集期貨並使用它們。 保留 100 個 Futures 的數組,然后在需要時循環它們收集結果,直到有足夠的結果滿足您的需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.