并发编程之Future设计模式 (未来设计模式)

通过子线程完成任务,调用之后直接返回,主线程继续下面的任务,等到子线程完成任务进行回调通知。
Future 用来代表未来的一个凭据
FutureTask 执行的任务逻辑
FutureService 桥接 Future和FutureTask
用于理解的实例:
早上10点去蛋糕店定做一个蛋糕,交完钱蛋糕店提供一个收据,凭借收据进行蛋糕的领取,做蛋糕需要时间,店员让你下午3点去拿蛋糕。
串行:一直等到下午三点蛋糕做好,蛋糕做好拿了蛋糕,再去做其他的事情。
并行wait:就是三点做好,而你一点就去在那等着,等到蛋糕做好后,你拿走再去做其他的事情
回调:你在定蛋糕的时候,留下了一个地址,等到做好后,店员会把根据地址把蛋糕送到,用收据作为标示
其中:做蛋糕->FutureTask , CallBack->具体地址 ,收据就是Future
具体实现代码:

public interface Future<T> {
    T get() throws InterruptedException;
}

public class AsyncFuture<T> implements Future{

    private volatile boolean done = false;
    private T result;

    public void done(final T future) {
        synchronized (this){
            done = true;
            result = future;
            this.notifyAll();
        }
    }

    @Override
    public T get() throws InterruptedException {
        synchronized (this){
            //这种方式会造成调用线程wait(),如果操作没有完成,这个调用线程会wait住,不能执行后续的操作
            while (!done){
                this.wait();
            }
        }
        System.out.println(Thread.currentThread());
        return result;
    }
}

public interface FutureTask<T> {
    T call() throws InterruptedException;
}

public class FutureService {

    //通过回调的方式,得到结果后自己去定义完成之后的操作
    public <T> void commit(final FutureTask<T> task, Consumer<T> customer){
        new Thread(()->{
            try {
                T call = task.call();
                customer.accept(call);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
    // 通过自己去调用,中间还是有可能等待的
    public <T> Future<T> commit(final FutureTask<T> task) {
        AsyncFuture<T> asyncFuture = new AsyncFuture<>();
        new Thread(()->{
            try {
                T call = task.call();
                asyncFuture.done(call);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        return asyncFuture;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值