Callable和Future实现多线程
Future取得的结构类型和Callable返回的结果类型必须一致。
Callable要采用ExecutorService的submit方法提交,返回的future对象可以取消任务
1.提交任务,得到任务的返回结果举例
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<String> future = threadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
return "hello";
}
});
future.get();
2.CompletionService用于提交一组Callable任务,其take方法返回已完成的一个Callable任务对应的
Future对象。就是一件事让多个线程去执行,谁先执行完,就取得谁的结果。例子如下:
ExecutorService threadPool2 = Executors.newFixedThreadPool(10);
CompletionService<String> completionService = new ExecutorCompletionService<String>
(threadPool2);
for (int i = 0; i < 10; i++) {
completionService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return "hello";
}
});
}
for (int i = 0; i < 10; i++) {
completionService.take().get();
}