多线程Future模式简单实现

在日常生活中,会经常遇到这样的例子,当某一件事情特别耗时,我们往往不会在原地等待,而是利用等待的时间去做其他事情。例如,需要定做一个生日蛋糕,我们只会去蛋糕店和师傅说一声,交完钱拿到票据,然后做自己的事情,过一段时间,拿着刚才的票据,就能拿到蛋糕了。多线程中也存在这样的模式,称之为future模式。

现在,简单的实现这样的模式。

首先定一个Future接口,这个接口只有一个get方法,用来获取结果。
public interface Future<T> {

    T get() throws InterruptedException;
}
定义FutureTask接口,这个接口用来抽象执行任务的具体逻辑。
public interface FutureTask<T> {

    T call();
}
定义AsyncFutureTask类,实现Future接口,实现get方法,当任务没有完成时调用get方法时,该方法wait
public class AsyncFutureTask<T> implements Future<T> {

    private volatile boolean isDone;
    private T result;

    @Override
    public T get() throws InterruptedException {
        synchronized (this) {
            while (!isDone) {
                this.wait();
            }
            return result;
        }

    }


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

    }


}
定义FutureService类,提供submit方法,将具体任务逻辑提交,这里开一个新的线程去执行该逻辑,保证不会阻塞。
public <T> Future<T> submit(FutureTask<T> task) {
        AsyncFutureTask<T> asyncFutureTask = new AsyncFutureTask<>();
        new Thread(() -> {
            asyncFutureTask.done(task.call());
        }).start();
        return asyncFutureTask;

    }
测试类
public class FutureTest {
    public static void main(String[] args) throws InterruptedException {
        FutureService service = new FutureService();
        Future<String> future = service.submit(() -> {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "done";
        });

        System.out.println("============");

        System.out.println(future.get());

    }
}
结果
============
done

Process finished with exit code 0

实现了future模式

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值