• FutureTask如何实现的阻塞返回的

    futureTask在使用get()函数的时候会阻塞等待返回

    1. /**
    2. * @throws CancellationException {@inheritDoc}
    3. */
    4. public V get() throws InterruptedException, ExecutionException {
    5. int s = state;
    6. if (s <= COMPLETING)
    7. s = awaitDone(false, 0L);
    8. return report(s);
    9. }

    可以看到这里使用的是awaitDone 进行阻塞,report 返回结果

    1. /**
    2. * Awaits completion or aborts on interrupt or timeout.
    3. *
    4. * @param timed true if use timed waits
    5. * @param nanos time to wait, if timed
    6. * @return state upon completion
    7. */
    8. private int awaitDone(boolean timed, long nanos)
    9. throws InterruptedException {
    10. final long deadline = timed ? System.nanoTime() + nanos : 0L;
    11. WaitNode q = null;
    12. boolean queued = false;
    13. for (;;) {
    14. if (Thread.interrupted()) {
    15. removeWaiter(q);
    16. throw new InterruptedException();
    17. }
    18. int s = state;
    19. if (s > COMPLETING) {
    20. if (q != null)
    21. q.thread = null;
    22. return s;
    23. }
    24. else if (s == COMPLETING) // cannot time out yet
    25. Thread.yield();
    26. else if (q == null)
    27. q = new WaitNode();
    28. else if (!queued)
    29. queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
    30. q.next = waiters, q);
    31. else if (timed) {
    32. nanos = deadline - System.nanoTime();
    33. if (nanos <= 0L) {
    34. removeWaiter(q);
    35. return state;
    36. }
    37. LockSupport.parkNanos(this, nanos);
    38. }
    39. else
    40. LockSupport.park(this);
    41. }
    42. }