多线程之Future设计模式

 

/**
 * Future         --> 代表的是未来的一个凭据
 * FutureTask     --> 将你的调用逻辑进行了隔离
 * FutureService  --> 桥接 Future和 FutureTask
 */
public class SyncInvoker {
    public static void main(String[] args) throws InterruptedException {
        FutureService futureService = new FutureService();
        //用了8的lambada特性,将行为一并传过去。
        Future<String> future = futureService.submit(
            () -> {
                try {
                    System.out.println("工作开始");
                    Thread.sleep(3000);
                    System.out.println("工作结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "最终的结果";
            });
        System.out.println("=====================");
        System.out.println("线程不会阻塞,可以做些别的工作。");
        System.out.println("=====================");
        System.out.println(future.get());
    }
}

 方法的接受者

//函数式接口,用来存放、传递逻辑执行单元。
public interface FutureTask<T> {
    T call();
}

拿结果传给桥接对象

public class FutureService {
    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;
    }
}

  输出结果

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

控制结果的输出

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;
            System.out.println("result: "+result);
            //修改通知表示符
            this.done = true;
            //通知阻塞的线程
            this.notifyAll();
        }
    }

    @Override
    public T get() throws InterruptedException {
        synchronized (this) {
            while (!done) {
                //如果没拿到结果,就让此线程等待。
                this.wait();
            }
        }
        return result;
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值