FutureTask源码阅读与理解

FutureTask源码阅读与理解

简述:FutureTask实现了Runnable和Future接口,代表此类可以被线程池调度和异步执行任务。

几个变量:

    //以下是state的几种状态
    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;

    //具体任务
    private Callable<V> callable;

    //任务执行完毕结果存放属性
    private Object outcome; 

    //记录执行任务的线程
    private volatile Thread runner;

    //链表结构,表示等待结果的线程
    private volatile WaitNode waiters;

几个方法:

//run方法就是执行任务的方法
public void run() {
        //判断state并试着去更新线程变量
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            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);
                }
                //如果执行成功则执行set方法
                if (ran)
                    set(result);
            }
        } finally {
            runner = null;
            int s = state;
            //判断state如果被中断则让出资源并等待被杀死
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

protected void set(V v) {
        //更新state状态为完成
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //结果赋值给outcome
            outcome = v;
            //最终状态
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL);
            //唤醒一些等待结果的线程
            finishCompletion();
        }
    }

private void finishCompletion() {
        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方法
        done();

        callable = null;        // to reduce footprint
    }

//获取数据的方法,可限时:
public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }
//具体的取值-等待方法
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);
                throw new InterruptedException();
            }

            //如果大于已完成则返回
            int s = state;
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            //说明执行任务的线程正在给outcome赋值,让掉cpu
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            //如果q==null那就创建一个等待节点
            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;
                }
                LockSupport.parkNanos(this, nanos);
            }
            //挂起线程
            else
                LockSupport.park(this);
        }
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值