Future<V>代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞。FutureTask<V>实现了Future<V>和Runable<V>。Callable代表一个有返回值得操作。
简单代码:
public class FutureTest { public static class Task implements Callable<String>{ @Override public String call() throws Exception { Thread.sleep(1800); System.out.println("ah"); return "something"; } } public static void main(String[] args) throws InterruptedException, ExecutionException { List<Future<String>> future = new ArrayList<Future<String>>(); ExecutorService service = Executors.newCachedThreadPool(); for (int i = 0; i < 100; i++) { future.add(service.submit(new Task())); } for (Future<String> future2 : future) { System.out.println(future2.get()); } } }
稍微复杂: 集合里面的数和,查看cpu数量,分开开线程
public class FutureTest1 { private ExecutorService exec; private int cpuCoreNumber; private List<Future<Long>> tasks = new ArrayList<Future<Long>>(); // 内部类 class SumCalculator implements Callable<Long> { private int[] numbers; private int start; private int end; public SumCalculator(final int[] numbers, int start, int end) { this.numbers = numbers; this.start = start; this.end = end; } public Long call() throws Exception { Long sum = 0l; for (int i = start; i < end; i++) { sum += numbers[i]; } return sum; } } public FutureTest1() { cpuCoreNumber = Runtime.getRuntime().availableProcessors(); exec = Executors.newFixedThreadPool(cpuCoreNumber); } public Long sum(final int[] numbers) { // 根据CPU核心个数拆分任务,创建FutureTask并提交到Executor for (int i = 0; i < cpuCoreNumber; i++) { int increment = numbers.length / cpuCoreNumber + 1; int start = increment * i; int end = increment * i + increment; if (end > numbers.length) end = numbers.length; SumCalculator subCalc = new SumCalculator(numbers, start, end); FutureTask<Long> task = new FutureTask<Long>(subCalc); tasks.add(task); if (!exec.isShutdown()) { exec.submit(task); } } return getResult(); } /** * 迭代每个只任务,获得部分和,相加返回 * * @return */ public Long getResult() { Long result = 0l; for (Future<Long> task : tasks) { try { // 如果计算未完成则阻塞 Long subSum = task.get(); result += subSum; } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } return result; } public void close() { exec.shutdown(); } public static void main(String[] args) { int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 }; FutureTest1 calc = new FutureTest1(); Long sum = calc.sum(numbers); System.out.println(sum); calc.close(); } }