当一个任务运行完和希望其返回一些信息,可以使用Callable和Future.
ExecutorService threadPool = Executors.newFixedThreadPool(2);
// 通过submit方法来提交一个Callable任务。
// Future 是用来接受call方法返回的结果。
Future<String> future = threadPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(5000);
return "hello hb";
}
});
// 在main线程上等待结果
System.out.println("等待结果:");
try {
// 通过get得到结果
System.out.println("拿到结果:" + future.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
还提交一组数据,由于线程的运行是不可知中,所以那个先运行完,我就拿那个的结果。相当于一个队列,先来行服务。
// 提交一组数据
ExecutorService threadPool2 = Executors.newFixedThreadPool(13);
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(
threadPool2);
for (int i = 0; i < 10; i++) {
final int task = i;
Future<Integer> future2 = completionService
.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(1000);
return task;
}
});
}
System.out.println("等待结果:");
for (int i = 0; i < 10; i++) {
try {
System.out.println("拿到结果:" + completionService.take().get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}