参考资料
(1) future.get方法阻塞问题的解决,实现按照任务完成的先后顺序获取任务的结果
(2) Java多线程引发的性能问题以及调优策略
(3) 可取消的异步任务——FutureTask用法及解析
(4) FutureTask源码解读
Future方法介绍
public interface Future<V> {
// 取消任务 可中断的方式取消
boolean cancel(boolean mayInterruptIfRunning);
// 判断任务是否处于取消状态
boolean isCancelled();
// 判断异步任务是否执行完成 ==这里使用轮训的方式监听==
boolean isDone();
// 获取异步线程的执行结果,如果没有执行完成,则一直阻塞到有结果返回;
V get() throws InterruptedException, ExecutionException;
// 获取异步线程的执行结果,如果没有执行完成,则一直阻塞到设置的时间,有结果返回,没有结果则抛出异常;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
简单示范Callable&Future
(1)向线程池中提交任务的submit方法不是阻塞方法,而Future.get方法是一个阻塞方法
(2)submit提交多个任务时,只有所有任务都完成后,才能使用get按照任务的提交顺序得到返回结果,所以一般需要使用future.isDone先判断任务是否全部执行完成,完成后再使用future.get得到结果。(也可以用get (long timeout, TimeUnit unit)方法可以设置超时时间,防止无限时间的等待)
public class FutureTest implements Callable<Integer> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
@Override
public Integer call() throws Exception {
System.err.println("start call method...");
Thread.sleep(3000);
return 1111;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.err.println("main method start....");
FutureTest futureTest = new FutureTest();
Future1Test future1Test = new Future1Test();
long time = System.currentTimeMillis();
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<String> future = executorService.submit(future1Test);
if (!future.isDone()) {
System.err.println("future not done !");
}
Future<Integer> future1 = executorService.submit(futureTest);
// submit提交多个任务时,只有所有任务都完成后,才能使用get按照任务的提交顺序得到返回结果
// 这里先提交了future1Test,休眠了4s, futureTest休眠了3s,