一、FutureTask对象的使用

当需要创建一个线程时,通常会有两种方式,实现Runnable 接口或者继承Thread 类,但不管使用这两种的那一个,线程执行后都不会有返回值,因为这俩的run方法都没有返回值。FutureTask对象就用来让一个线程执行完任务后可以有返回值,想获取这个返回值的线程在此线程没结束前会被阻塞住。

@Slf4j
public class Test1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> task = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(3000);
                log.info("task end ");
                return "success";
            }
        });

        Thread t1 = new Thread(task);
        t1.start();
        //主线程调用get方法后如何t1还没有返回结果主线程就会被阻塞住
        String res = task.get();
        log.info("res:{}",res);
    }
}

所以用FutureTask对象创建线程实现了让一个线程t1等待另一个线程t2的返回值的效果。

二、FutureTask源码解读

// 实现了Runnable接口所以可以用来创建线程
public class FutureTask<V> implements RunnableFuture<V> {
    // FutureTask内部维护的状态变量,表示当前对象的状态
    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; // non-volatile, protected by state reads/writes
    //存储当前对象会被那个线程执行
    private volatile Thread runner;
    
    //等待队列,任务未执行完前获取值的线程都会在这里阻塞(调用park方法)
    private volatile WaitNode waiters;
    
    //线程启动时执行的方法
    public void run() {
        //先校验当前对象的状态是不是New,不是就直接返回,线程就会结束运行;
        //使用cas操作把当前对象的runner属性设置成当前线程本身,如果失败了就直接返回
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            //callable封装了要执行的任务
            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);
                }
                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);
        }
    }
    
    //处理任务正常结束的情况
    protected void set(V v) {
        //cas操作设置state状态为COMPLETING
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;//返回值赋值
            //操作内存的方式设置状态为完成
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }
    
    //这个方法中会唤醒当前正在等待此线程返回值的其他线程
    private void finishCompletion() {
        // assert state > COMPLETING;
        //遍历等待链表
        for (WaitNode q; (q = waiters) != null;) {
            //修改链表头为null,防止其他线程也来遍历
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                for (;;) {
                    //以下从链表中取出每个线程用unpark方法唤醒
                    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
    }
    
    //异常情况的处理
    protected void setException(Throwable t) {
        //cas操作设置状态为COMPLETING
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //返回值设置为异常对象
            outcome = t;
            //设置状态为EXCEPTIONAL
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            //唤醒等待者
            finishCompletion();
        }
    }
    
    //以上这些就是线程执行FutureTask对象的过程,执行完后会把结果放到outcome属性中,
    //接下来看下另一个线程是如何获取此线程的返回值的
    
    //需要等待此FutureTask对象执行结果的线程调用此方法
    public V get() throws InterruptedException, ExecutionException {
        //获取当前状态
        int s = state;
        //状态值小于等于COMPLETING表示还未执行完,当前线程就需要阻塞等待
        if (s <= COMPLETING)
            //实现等待的效果
            s = awaitDone(false, 0L);
        //返回结果
        return report(s);
    }
    
    //实现等待的效果
    private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;//定义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;
                //返回状态,后续report方法会用到这个值
                return s;
            }
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)
                //创建一个链表节点赋值给q,下次循环会把q加入链表
                q = new WaitNode();
            else if (!queued)
                //把q加入等待队列
                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);
        }
    }
}