手写 Future 模式

Future 接口:

public interface Future<T> {

    T get() throws InterruptedException;
    boolean isDone();
    void Cancel();
    boolean isCancel();
}

 

FutureTask类:

public class FutureTask<T> implements Future<T> {

    private volatile boolean done = false;
    private boolean cancel = false;
    private T result;

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

    protected void done(T result){
        synchronized (this){ //2.
            this.result = result;
            this.done = true;
            notifyAll();
        }
    }

    @Override
    public boolean isDone() {
        return done;
    }

    @Override
    public boolean isCancel() {
        return cancel;
    }

    @Override
    public void Cancel() {

    }
}

1 处 2 处加 synchronized 的原因:如果不加 synchronized,尝试获取结果时,但此时还没返回结果,只能 while 自旋等待,这不耗费资源吗?加上 synchronized,没结果就释放资源挂起,等待有了结果,再去唤醒。

 

FutureService类:

public class FutureService<T> {

    public Future submit(Callable<T> callable)  {
        final FutureTask<T> task = new FutureTask();
        new Thread(()->{
            T result = null;
            try {
                result = callable.call();
            } catch (Exception e) {
                e.printStackTrace();
            }
            task.done(result);
        }).start();
        return task;
    }
}

 

测试类:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client {
    public static void main(String[] args) throws Exception {
        FutureService service = new FutureService();

        Future<String> future = service.submit(new Callable() {
            @Override
            public String call() throws InterruptedException {
                System.out.println("call start");
                Thread.sleep(5000);
                return "call end";
            }
        });

        Thread.sleep(1000);
        System.out.println("Thread main do other things");

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值