![](/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.