多线程中Future的原理

通过Future 异步回调,不阻塞下面的执行,并且在方法最后执行完毕前,调用方法或通过回调的方法获取返回值。
其核心其实就是创建一个线程

这也是多线程的一个设计模式

public interface Future<T> {

    T get() throws InterruptedException;
}

这边在方法中添加synchronized 关键字,就是防止多线程问题。

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

这个接口看似平平无奇,却是将你的调用逻辑进行了隔离

public interface FutureTask<T> {

    T call() throws InterruptedException;
}

建service,实现方法

public class FutureService {

    public <T> Future<T> submit(final FutureTask<T> task, final Consumer<T> consumer){
        AsynFuture asynFuture = new AsynFuture();
        // 这里的线程就是整个设计模式的关键,添加变量final Consumer<T> consumer 建立回调
        new Thread(() -> {
            T result = null;
            try {
                result = task.call();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            asynFuture.done(result);
            consumer.accept(result); 
        }).start();
        return asynFuture;
    }
}

测试类

public static void main(String[] args) throws InterruptedException {
        FutureService futureService = new FutureService();
        String temp = null;
        Future<String> future = futureService.submit(() -> {
          Thread.sleep(1000);
          return "Finish";
        },(a) -> {  // 这里把上面代码的Consumer 改成了 Function 函数了。所以不要照搬着看
            System.out.println(a + " ===");
            return a;
        });

//        System.out.println("=============");
//        System.out.println(future.get());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值