Callable+Future
Posted moris5013
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Callable+Future相关的知识,希望对你有一定的参考价值。
Future提供了三种功能:
1)判断任务是否完成;
2)能够中断任务;
3)能够获取任务执行结果
package com.moreas; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class TestCallable { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); Task task = new Task(); Future<Integer> result = executor.submit(task); //这里只是将空闲的线程中断,将线程池的状态改为shutdown,不能继续往线程池中添加任务 executor.shutdown(); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.println("主线程在执行任务"); try { System.out.println("task运行结果" + result.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println("所有任务执行完毕"); } } class Task implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("子线程在进行计算"); Thread.sleep(3000); int sum = 0; for (int i = 0; i <= 100; i++) sum += i; return sum; } }
以上是关于Callable+Future的主要内容,如果未能解决你的问题,请参考以下文章
原创JAVA并发编程——Callable和Future源码初探