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()); } }