手写FutureTask


首先继承 Runnable  Future 接口然后实现  我们只需要 用到run() 和get()方法就可以其它不用看
 this.wait(); 调用这个方法让它阻塞,一致等到结果 然后调用notifyAll() 唤醒线程.
import java.util.concurrent.*;

public class JxdFutureTask<V> implements Runnable, Future<V> {

    Callable<V> callable;
    V result = null;

    //构造方法
    public JxdFutureTask(Callable<V> callable) {
        this.callable = callable;
    }

    @Override
    public void run() {
        try {
            result =this.callable.call();
            synchronized (this){
                this.notifyAll();//唤醒阻塞等待的线程
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //需要实现,跑业务
    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

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

    @Override
    public V get() throws InterruptedException, ExecutionException {
        return null;
    }


    /**
     * 处理返回结果
     */
    @Override
    public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (null != result) {
            return result;
        }
        //否则的话让它阻塞等待结果
        synchronized (this){
           this.wait();
        }
        //执行到这里标识被唤醒 ,被唤醒意味着有值了
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值