FutureTask 从源码分析为什么会线程阻塞

FutureTask 继承关系如下

public FutureTask<V> implements RunnableFuture<V> {

      public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

      public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

}
public interface RunnableFuture<V> extends Runnable, Future<V>
public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    //这里面比较关键就是get方法,也是这个blog的重点
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

实例demo

FutureTask task = new FutureTask(new Callable(){

    public Object call(){
        //....
        return new Object();
    }
});
task.run();
//这步会阻塞等待
task.get();

问题:为什么线程会在task.get()阻塞等待?

由上面继承关系可知道FutureTask 继承线程,那么必然会有run方法的实现

FutureTask里的run()

public void run() {
        //第一个条件:FutureTask  构造方法里可知道state=NEW ,如果不满足就return 
        //第二个条件 : 多线程的情况下,cas去争抢runnerOffset,也就是private volatile Thread runner;
        //runnerOffset是private volatile Thread runner的一个内存地址,将当前线程设入到runner这个变量里,没抢到的就return了
        //这个保证了多线程下FutureTask的线程安全
        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 {
                    //调用上面实例中的call方法
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                //如果完成了设置result
                if (ran)
                    set(result);
            }
        } finally {
            ...
        }
    }

分析完上面的run方法后就到了关键的get方法

    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            //!!!关键的awaitDone,会阻塞等待
            s = awaitDone(false, 0L);
        return report(s);
    }
  //从名字看就是等待完成,这是为什么线程会阻塞的方法
     private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        //如果timed为true,就是等待多长时间还没完成的话就直接返回了
        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;
            }
            else if (s == COMPLETING) //完成中,线程也没必要那么积极了
                Thread.yield();
            else if (q == null)
            //将线程放到一个WaitNode里
                q = new WaitNode();
            else if (!queued)
            //没排队的话,将自己排到链表的最前面,并且调用cas将自己替换到waiters里
                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
               //阻塞等待unpark LockSupport.park(this);
        }
    }


    //WaitNode是个单链表的结构,类似AQS 里的线程等待队列
    static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }

上面的get()方法会使得线程等待,如果超时就抛出超时异常。上面时候线程会唤醒呢?看run()里的set(result)

  protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    } 



    private void finishCompletion() {
      //waiters就是前面的set里利用cas设入的waitNode
        for (WaitNode q; (q = waiters) != null;) {
            //先将waiters设成null
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
            //遍历单链表,依次去unpark,也就是唤醒线程,直到尾部
                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
    }

猜你喜欢

转载自blog.csdn.net/guo_xl/article/details/79605578