zoukankan      html  css  js  c++  java
  • Future模式

    1引论   

         什么是Future模式呢?Future 顾名思义,在金融行业叫期权,市场上有看跌期权和看涨期权,你可以在现在(比如九月份)购买年底(十二月)的石油,假如你买的是看涨期权,那么如果石油真的涨了,你也可以在十二月份依照九月份商定的价格购买。扯远了,Future就是你可以拿到未来的结果。对于多线程,如果线程A要等待线程B的结果,那么线程A没必要等待B,直到B有结果,可以先拿到一个未来的Future,等B有结果是再取真实的结果。其实这个模式用的很多,比如浏览器下载图片的时候,刚开始是不是通过模糊的图片来代替最后的图片,等下载图片的线程下载完图片后在替换。如图所示:Future

    2 思想

    Future

    一個簡單的Java程式片段示範可能像是這樣:

    ....

     public Future request() {
        final Future future = new Future();

        new Thread() {
            public void run() {
                // 下面這個動作可能是耗時的
                RealSubject subject = new RealSubject();
                future.setRealSubject(subject);
            }
        }.start();

        return future;
     }

          可是我要怎么判断我要的数据已经准备好?
          
    通过自定义一个结果类,负责结果持有。
          
                public  class  FutureResult{
              
                         private  String  result;
              private  boolean  isFinish  =  false;
                    
                         public  String  getResult(){
                   return  result;
                    }
              
                         public  synchronized  void  setResult (String  result){
                   this.result  =  result;
                   this.isFinish  =  true;
                    }
              
                         public  synchronized  boolean  isFinish(){
                   return isFinish;
                    }
                         }



    3 Just do it

        
        
        Future对象本身可以看作是一个显式的引用,一个对异步处理结果的引用。由于其异步性质,在创建之初,它所引用的对象可能还并不可用(比如尚在运算中,网络传输中或等待中)。这时,得到Future的程序流程如果并不急于使用Future所引用的对象,那么它 可以做其它任何想做的事儿,当流程进行到需要Future背后引用的对象时,可能有两种情况:
    •     希望能看到这个对象可用,并完成一些相关的后续流程。如果实在不可用,也可以进入其它分支流程。
    •       “没有你我的人生就会失去意义,所以就算海枯石烂,我也要等到你。”(当然,如果实在没有毅力枯等下去,设一个超时也是可以理解的)
          对于前一种情况,可以通过调用Future.isDone()判断引用的对象是否就绪,并采取不同的处理;
          后一种情况则只需调用get()或get(long timeout, TimeUnit unit)通过同步阻塞方式等待对象就绪。实际运行期是阻塞还是立即返回就取决于get()的调用时机和对象就绪的先后了。(如下图所示)
         Future
        
         总之,FutureTask封装了对realObject(Callable实例)的异步和同步操作,持有Callable实例,线程执行FutureTask对象

         下面的例子模拟的是一个会计算账的过程,主线程中已经获得其他帐户的总额了,为了不让主线程等待PrivateAccount 返回而启用新的线程去处理,并使用 FutureTask 对象来监控,最后需要计算总额的时候再尝试去获得PrivateAccount 的信息。
    • SumAccountExample.java

    package com.gc.pattern;

    import  java.util.Random;
    import  java.util.concurrent.Callable;
    import  java.util.concurrent.ExecutionException;
    import  java.util.concurrent.FutureTask;

    public   class  SumAccountExample  {

         public   static   void  main(String[] args)  {
             //  Init callable object and future task
             Callable pAccount = new PrivateAccount();
             FutureTask futureTask = new FutureTask(pAccount);
             
              //  Create a new thread to do so
             Thread pAccountThread = new Thread(futureTask);
             pAccountThread.start();
             
             //  Do something else in the main thread
             System.out.println("Doing something else here.");
             
              //  Get the total money from other accounts 
             int totalMoney = new Random().nextInt(100000);
             System.out.println("You have "+totalMoney+" in your other Accounts.");
             System.out.println("Waiting for data from Private Account");
              //  If the Future task is not finished, we will wait for it
             while (!futureTask.isDone()){
                  try{
                     Thread.sleep(5);
                    }
                  catch(InterruptedException e){
                     e.printStackTrace();
                 }
             }
             Integer privataAccountMoney = null ;
              //  Since the future task is done, get the object back
             try{
                 privataAccountMoney = (Integer)futureTask.get();
             }
             catch(InterruptedException e){
                 e.printStackTrace();
             }
             catch(ExecutionException e){
                 e.printStackTrace();
             }
             System.out.println("The total moeny you have is "+(totalMoney+privataAccountMoney.intValue()));
         }

     }
    • PrivateAccount.java

    package com.gc.pattern;

    import java.util.Random;
    import java.util.concurrent.Callable;
    class PrivateAccount implements Callable{
          
          Integer totalMoney;
          public  Integer call()  throws  Exception  {
                  //  Simulates a time conusimg task, sleep for 10s
                  //与Callable 不同,它有返回值
                 Thread.sleep( 10000 );
                 totalMoney  = new Integer(new Random().nextInt(10000));
                 System.out.println("You have "+totalMoney+"  in your private Account. " );
                 return  totalMoney;
             }
             
         } 

  • 相关阅读:
    Ajax中XML和JSON格式的优劣比较
    多语言的网站怎么做呀
    asp.net 2.0多语言网站解决方案
    FrameSet 与 IFrame 彻底剖析
    概要设计说明书
    用C#如何实现大文件的断点上传!
    PowerDesigner生成sql生成不了
    TransactionScope的正确用法
    iframe
    动网转型网游一年获得成功:每月盈利超500万
  • 原文地址:https://www.cnblogs.com/yangkai-cn/p/4017260.html
Copyright © 2011-2022 走看看