前面说到Callable和Future。 每一个Callable都会返回一个Future.
但是如果ExecutorService启动了多个callable,那么我们就需要处理多个Future,这个时候就应该用到CompletionService
ExecutorService exe2 = Executors.newFixedThreadPool(10);
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(exe2);
for(int i=0;i<10;i++){
final int seq=i;
completionService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(new Random().nextInt(5000));
return seq;
}
});
}
for(int i=0;i<10;i++){
try {
int ret =completionService.take().get();
System.out.println(ret);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
7
3
0
2
6
9
1
8
5
4