Java FutureTask,Future,callable

Java FutureTask,Future,callable

1.Future接口

来自官方文档 (Java 8)

Future

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.

以及方法

Modifier and TypeMethod and Description
booleancancel(boolean mayInterruptIfRunning)Attempts to cancel execution of this task.
Vget()Waits if necessary for the computation to complete, and then retrieves its result.
Vget(long timeout, TimeUnit unit)Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.
booleanisCancelled()Returns true if this task was cancelled before it completed normally.
booleanisDone()Returns true if this task completed.

2.FutureTask类关系

在这里插入图片描述

Runnable是线程类必须实现的接口。

Callable接口只有一个call()方法,类似与Runnable接口的run()方法,只不过call方法有返回值。

FutureTask适配了CallableRunnable接口(FutureTask内部聚合了一个Callable)

1.相关变量:
/** The underlying callable; nulled out after running */
private Callable<V> callable;
/** The result to return or exception to throw from get() */
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
private volatile Thread runner;
/** Treiber stack of waiting threads */
private volatile WaitNode waiters;
2.相关状态以及状态之间的转换:
/* Possible state transitions:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
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.内部类WaitNode
static final class WaitNode {
    volatile Thread thread;
    volatile WaitNode next;
    WaitNode() { thread = Thread.currentThread(); }
}

3.FutureTask函数说明

1.run()
//FutureTask是一个Runnable,即Runnable的run()方法。
public void run() {
    if (state != NEW ||
        !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                     null, Thread.currentThread()))//通过cas将当前线程交给runner成员变量。
        return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
                setException(ex);//outcome = ex。并设置状态为NEW -> COMPLETING -> EXCEPTIONAL
            }
            if (ran)//如果运行成功
                set(result);//outcome = t。并设置状态为NEW -> COMPLETING -> NORMAL
        }
    } 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);
    }
}
2.finishCompletion()
/**
 * Removes and signals all waiting threads, invokes done(), and
 * nulls out callable.
 */
private void finishCompletion() {
    // assert state > COMPLETING;
    for (WaitNode q; (q = waiters) != null;) {
        if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
            for (;;) {
                Thread t = q.thread;
                if (t != null) {
                    q.thread = null;
                    LockSupport.unpark(t);
                }
                WaitNode next = q.next;
                if (next == null)
                    break;
                q.next = null; // unlink to help gc
                q = next;
            }
            break;
        }
    }
    done();
    callable = null;        // to reduce footprint
}
3.cancel()
public boolean cancel(boolean mayInterruptIfRunning) {
    //只有状态是NEW才可以cancel,并将状态改为INTERRUPTING或者CANCELLED(根据参数mayinterruptifRunning)
    if (!(state == NEW &&
          UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
              mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
        return false;
    try {    // in case call to interrupt throws exception
        if (mayInterruptIfRunning) {
            try {
                Thread t = runner;
                if (t != null)
                    t.interrupt();//设置中断标志
            } finally { // final state
                UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);//设置状态
            }
        }
    } finally {
        finishCompletion();//唤醒所有等待的线程
    }
    return true;
}
4.get()
//获取call()结果,或者返回异常
public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);//线程还没有计算完成,则加入阻塞队列等待
    return report(s);
}
//report(s)
 private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)//正常结束返回结果,callable.call()的结果
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
   }
5.awaitDone()
//为当前线程构建一个WaitNode并等待
private int awaitDone(boolean timed, long nanos)
    throws InterruptedException {
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    WaitNode q = null;
    boolean queued = false;
    for (;;) {
        if (Thread.interrupted()) {
            removeWaiter(q);线程被中断的情况下,从waiters链表中删除q
            throw new InterruptedException();
        }

        int s = state;
        if (s > COMPLETING) {//工作线程完成了或者(中断,退出,异常),则返回当前线程
            if (q != null)
                q.thread = null;
            return s;
        }
        else if (s == COMPLETING) // cannot time out yet//让出cpu时间,注意让出后该线程只是从运行态->就绪态。
            Thread.yield();
        else if (q == null)//为当前线程构建节点
            q = new WaitNode();
        else if (!queued)//从等待队列头部插入上面构建的节点。头插法
            queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                 q.next = waiters, q);
        else if (timed) {//当前线程设置了最长等待时间,则等待时间到了从队列移除该线程。
            nanos = deadline - System.nanoTime();
            if (nanos <= 0L) {
                removeWaiter(q);
                return state;
            }//该线程等待nanos时间。
            LockSupport.parkNanos(this, nanos);
        }
        else//该线程等待。
            LockSupport.park(this);
    }
}

4.用法与实现分析

1.用法

在这里插入图片描述

2.等待队列

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值