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

     Future设计模式把同步调用变成异步调用

    //表示一个可能还没有完成的异步任务的结果,直接返回给调用者
    public interface Future<T> {
    
        T get() throws InterruptedException;
    
    }
    //Future具体的实现
    public class AsynFuture<T> implements Future<T> {
    
        private volatile boolean done = false;
    
        private T result;
    
        public void done(T result) {
            synchronized (this) {
                this.result = result;
                this.done = true;
                this.notifyAll();
            }
        }
    
        @Override
        public T get() throws InterruptedException {
            synchronized (this) {
                while (!done) {
                    this.wait();
                }
            }
            return result;
        }
    }
    //要提交的异步任务,执行逻辑由子类覆写call方法
    public interface FutureTask<T> {
    
        T call();
    }
    //桥接Future和FutureTask
    public class FutureService {
    
        //调用者通过Future来获取结果
        public <T> Future<T> submit(final FutureTask<T> task) {
            AsynFuture<T> asynFuture = new AsynFuture<>();
            new Thread(() -> {
                T result = task.call();
                asynFuture.done(result);
            }).start();
            return asynFuture;
        }
    
      //调用者通过Future来获取结果或者由回调函数来处理
        public <T> Future<T> submit(final FutureTask<T> task, final Consumer<T> consumer) {
            AsynFuture<T> asynFuture = new AsynFuture<>();
            new Thread(() -> {
                T result = task.call();
                asynFuture.done(result);
                consumer.accept(result);
            }).start();
            return asynFuture;
        }
    }
    public class Client {
    
        public static void main(String[] args) throws InterruptedException {
    
            FutureService futureService = new FutureService();
            //通过回调函数通知调用者
    //        futureService.submit(() -> {
    //            try {
    //                Thread.sleep(10000L);
    //            } catch (InterruptedException e) {
    //                e.printStackTrace();
    //            }
    //            return "FINISH";
    //        }, System.out::println);
    
            //调用者主动获取结果,可能会发生阻塞
            Future<String> future = futureService.submit(()->{
                try {
                    Thread.sleep(5000L);
                }catch(Exception e) {
                    e.printStackTrace();
                }
                return "ABC";
            });
            
            System.out.println("===========");
            Thread.sleep(2000);
            System.out.println("######## "+future.get());
        }
    }

     

  • 相关阅读:
    开源交易所源码搜集
    域名
    国外大牛博客
    Fomo3D代码分析以及漏洞攻击演示
    Small组件化重构安卓项目
    html span和div的区别
    七牛云
    以太坊钱包安全性保证
    跨域问题
    checkout 到bit/master分支
  • 原文地址:https://www.cnblogs.com/moris5013/p/10917120.html
Copyright © 2011-2022 走看看