Java中Callable和Future——引子

来源:互联网 发布:centos kali双系统 编辑:程序博客网 时间:2024/06/05 10:13

一、场景


通常我们在一个事件方法中会去调用另外几个方法,如发用邮件,为了快速响应,一般最简单直接粗暴的是
新启一线程来异步发邮件(使用线程池较好)。这个时候我们不太在意所依赖的方法操作成功与否(即不需要结果)。

但,多半我们是需要异步操作结果的。比如在Action层调用多个Service或在Service层方法中调用多个DAO。如下图,假设某Action层方法需要依赖调用a、b、c三个方法,它们三分别耗时10ms、15ms、20ms,这样串行顺序执行下来,即总共需要45ms。
这里写图片描述

有木有办法缩短这个耗时呢?


二、方法


如果使a、b、c并发执行,怎么样?那么总共耗时就是这三个中耗时最长的那一个即20ms。如下图:
这里写图片描述

我们知道线程Runnable接口是没返回结果的。看看下面的Callable和Future简单模拟实现:

import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/**   * * @author : Ares.yi * @createTime : 2014-11-10 上午11:13:42  * @version : 1.0  * @description :  * */public class TestFuture {    private final ExecutorService pool = Executors.newFixedThreadPool(2);    public int getData() throws Exception{        int i = invoke1();        int j = invoke2();        return i+j;    }    public int getData2() throws Exception{        Future<Integer> f1 = null;        Future<Integer> f2 = null;        f1 = pool.submit(new Callable<Integer>() {            @Override            public Integer call() throws Exception {                return invoke1();            }        });        f2 = pool.submit(new Callable<Integer>() {            @Override            public Integer call() throws Exception {                return invoke2();            }        });        int i = f1.get();//会阻塞        int j = f2.get();        pool.shutdown();        return i+j;    }    public static void main(String[] args) throws Exception {        TestFuture obj = new TestFuture();        long start = System.currentTimeMillis();        obj.getData2();        long end = System.currentTimeMillis();        System.out.println(end-start);    }    private static int invoke1() throws InterruptedException{        Thread.sleep(3000);        return 1;    }    private static int invoke2() throws InterruptedException{        Thread.sleep(2000);        return 2;    }}

三、延伸


如果c需要依赖a和b的结果呢,怎么办?
这里写图片描述

请见最后一篇。