美文网首页Java程序性能优化
并行模式之Future模式

并行模式之Future模式

作者: Chinesszz | 来源:发表于2017-07-15 22:53 被阅读32次

    理论

    所谓 future 模式就是将任务提交给后台线程,然后主线程继续进行其他任务,当调用任务返回数据的时候,如果任务还未返回就阻塞等待任务。

    举个例子:

    一个人上街买西瓜汁(5min)🍉和馒头(1min)

    • 传统方式:

    因为西瓜汁要榨所以要等待5分钟,而馒头是做好的不用等待,传统方式是:先买西瓜,就等5分钟,然后再买馒头。总共耗时:5+1

    • Future模式:

    让西瓜汁先做,然后自己去买馒头,回来,在等4分钟,也就是并行计算
    总共耗时:5分钟

    分析:为何会阻塞

    原因就是变量等待被赋值,一直阻塞在某一行,那么如果不想被阻塞,那么当调用方法直接就返回,那么就不会被阻塞了。

    于是我们将直接调用方法进行包装,当线程调用返回,会立即返回结果。当对结果进行处理的时候(判断这是数据是否已经返回,如过没有返回,那么久阻塞)才会真正被阻塞。

    代码实现

    public interface Data {
        String getResult() throws InterruptedException;
    }
    
    public class RealData implements Data {
        protected String data;
    
        RealData(String data){
            this.data=data;
        }
    
        public String getResult() throws InterruptedException {
            return data;
        }
    }
    
    
    public class FutureData implements Data {
        RealData realData = null;
    
        boolean isReady = false;//是否已经准备好
    
        public synchronized void setRealData(RealData realData){
            //如果已经好了,就直接返回
            if (isReady){
                return;
            }
            this.realData=realData;
            isReady=true;
            notifyAll();//唤醒线程,准备返回参数
        }
    
        public String getResult() throws InterruptedException {
            //没有准备好久等待
            if (!isReady) {
                wait();
            }
            return realData.getResult();
        }
    }
    

    JDK中如何实现

    • 1.集成Callable<String/Dto>
    • 2.重写call方法
    /**
     * @Package: com.future.built
     * @Description: 内置方法
     * 将任务交给线程去提交执行
     * @author: liuxin
     * @date: 2017/7/11 上午11:27
     */
    public class Main {
        public static void main(String[] args) throws Exception{
            FutureTask<String> future=new FutureTask<String>(new RealData("2"));
            ExecutorService executor = Executors.newFixedThreadPool(1);
            executor.submit(future);
            executor.shutdown();
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
            }
            System.out.println(future.get());
        }
    }
    
    

    相关文章

      网友评论

        本文标题:并行模式之Future模式

        本文链接:https://www.haomeiwen.com/subject/vhgzhxtx.html