使用示例
定义Callable:
Callable<Integer> callable = () -> {
System.out.println("子线程在进行计算");
Thread.sleep(3000);
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
return sum;
};
Callable+Future
void testCallableFuture() throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
System.out.println("main------开始计算");
//实际上此时Future的具体实现类为: FutureTask
Future<Integer> future = executor.submit(callable);
int result = future.get();
System.out.println("main------计算完成:"+result);
}
执行结果:
Callable+FutureTask ----ThreadPool
void testCallableFutureTask() throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
System.out.println("main------开始计算");
FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
executor.submit(futureTask);
//直接通过futureTask,即可获取结果
int result = futureTask.get();
System.out.println("main------计算完成:"+result);
}
Callable+FutureTask ----Thread
FutureTask还可以脱离线程池使用:
void testCallableFutureTask2() throws ExecutionException, InterruptedException {
System.out.println("main------开始计算");
FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
//直接使用线程
new Thread(futureTask).start();
int result = futureTask.get();
System.out.println("main------计算完成:"+result);
}