FutureTask

FutureTask

1 用途

A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled (unless the computation is invoked using runAndReset())

提供可以开始和取消的异步任务、并且执行结束后能够获取执行的结果,一旦执行结束后就不能够重新开始或取消。

2 实现

FutureTask实现了RunnableFuture接口

FutureTask

既然是任务首先看run方法

 public void run() {
        //查看状态,如果不是new说明已经执行,如果是则cas设置worker thread为当前线程  
               //确保任务只被执行一次
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            //将构造函数中构造的callable拿出
            Callable c = callable;
            if (c != null && state == NEW) {    //callable不为空、状态为new则执行
                V result;
                boolean ran;
                try {
                    result = c.call();  //执行call
                    ran = true;
                } catch (Throwable ex) {    //执行出错处理异常
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);    //正常执行则设置返回返回值
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;  
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

get方法获取返回值

public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)    //如果未完成则进入阻塞队列
        s = awaitDone(false, 0L);
    return report(s);   //根据完成情况获取结果
}

FutureTask根据任务的状态判断任务执行的情况,状态以及它们之间的转换如下

    /**
     * The run state of this task, initially NEW.  The run state
     * transitions to a terminal state only in methods set,
     * setException, and cancel.  During completion, state may take on
     * transient values of COMPLETING (while outcome is being set) or
     * INTERRUPTING (only while interrupting the runner to satisfy a
     * cancel(true)). Transitions from these intermediate to final
     * states use cheaper ordered/lazy writes because values are unique
     * and cannot be further modified.
     *
     * Possible state transitions:
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
     */
    private volatile int state;
    private static final int NEW          = 0;  //新建
    private static final int COMPLETING   = 1;  //执行中
    private static final int NORMAL       = 2;  //正常执行完
    private static final int EXCEPTIONAL  = 3;  //执行异常
    private static final int CANCELLED    = 4;  //取消
    private static final int INTERRUPTING = 5;  //正在等待响应中断
    private static final int INTERRUPTED  = 6;  //已中断

3 小结

run方法中将构造 函数中的callable拿出执行,执行结果放入实例变量outcome中,get则去取出outcome,根据state进行通信判断任务执行情况。

你可能感兴趣的:(FutureTask)