FutureTask创建Future
本文演示通过FutureTask去创建Future.
概述
我们通过类图去说明FutureTask,见下图所示
FutureTask实例
下面我们通过一个代码去演示FutureTask用法,见下图所示:
package com.yang.callable; import java.util.concurrent.*; public class FutureTaskDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(2); FutureTask<Integer> futureTask = new FutureTask<>(new Task()); executorService.submit(futureTask); System.out.println(futureTask.get()); executorService.shutdown(); } static class Task implements Callable<Integer> { @Override public Integer call() throws Exception { int num = 0; for (int i = 0; i < 10000; i++) { num = num + i; } return num; } } }
运行结果如下: