类关系图

image.png
FutureTask实现了RunableFuture接口。间接实现了Runable接口和Funture。所以他也是可以丢给线程去执行

构造器

  1. public FutureTask(Callable<V> callable) {
  2. if (callable == null)
  3. throw new NullPointerException();
  4. this.callable = callable;//真正执行的方法
  5. this.state = NEW; // ensure visibility of callable 确保callable的可见性
  6. }

构造器初始化的时候要传一个Callable,这个是我们程序真正要执行的方法

Callable接口

  1. @FunctionalInterface
  2. public interface Callable<V> {
  3. V call() throws Exception;
  4. }

需要执行的方法类去实现callable这个接口,并返回结果

run()线程调度的方法

  1. public void run() {
  2. if (state != NEW ||
  3. !UNSAFE.compareAndSwapObject(this, runnerOffset,
  4. null, Thread.currentThread()))
  5. return;
  6. try {
  7. Callable<V> c = callable;//构造器传过来的需要完成的任务
  8. if (c != null && state == NEW) {
  9. V result;
  10. boolean ran;
  11. try {
  12. result = c.call();//执行任务
  13. ran = true;
  14. } catch (Throwable ex) {
  15. result = null;
  16. ran = false;
  17. setException(ex);//设置异常
  18. }
  19. if (ran)
  20. set(result);//设置结果
  21. }
  22. } finally {
  23. // runner must be non-null until state is settled to
  24. // prevent concurrent calls to run()
  25. runner = null;
  26. // state must be re-read after nulling runner to prevent
  27. // leaked interrupts
  28. int s = state;
  29. if (s >= INTERRUPTING)
  30. handlePossibleCancellationInterrupt(s);
  31. }
  32. }

调用.state启动线程后,cpu会去调用run方法。run方法调用call去执行真正的任务

set(V v)保存结果

  1. protected void set(V v) {
  2. if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {//cas保证线程安全
  3. outcome = v;//保存结果
  4. UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state 设置最终状态
  5. finishCompletion();//唤醒get的时候阻塞的线程
  6. }
  7. }

finishCompletion() 唤醒等待结果的线程

  1. private void finishCompletion() {
  2. // assert state > COMPLETING;
  3. for (WaitNode q; (q = waiters) != null;) {
  4. if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {//cas
  5. for (;;) {
  6. Thread t = q.thread;
  7. if (t != null) {
  8. q.thread = null;
  9. LockSupport.unpark(t);//唤醒线程
  10. }
  11. WaitNode next = q.next;
  12. if (next == null)
  13. break;
  14. q.next = null; // unlink to help gc
  15. q = next;
  16. }
  17. break;
  18. }
  19. }
  20. done();
  21. callable = null; // to reduce footprint
  22. }

V get() 获取结果

  1. public V get() throws InterruptedException, ExecutionException {
  2. int s = state;
  3. if (s <= COMPLETING)//结果还未出来
  4. s = awaitDone(false, 0L);//进入等待
  5. return report(s);//获取结果
  6. }

awaitDone(boolean timed, long nanos)等待执行任务完成

  1. private int awaitDone(boolean timed, long nanos)
  2. throws InterruptedException {
  3. final long deadline = timed ? System.nanoTime() + nanos : 0L;//超时等待
  4. WaitNode q = null;
  5. boolean queued = false;
  6. for (;;) {
  7. if (Thread.interrupted()) {//中断标记
  8. removeWaiter(q);
  9. throw new InterruptedException();
  10. }
  11. int s = state;
  12. if (s > COMPLETING) {//线程结束
  13. if (q != null)
  14. q.thread = null;
  15. return s;
  16. }
  17. else if (s == COMPLETING) // cannot time out yet 马上结束了
  18. Thread.yield();
  19. else if (q == null)
  20. q = new WaitNode();//创建一个等待节点
  21. else if (!queued)
  22. queued = UNSAFE.compareAndSwapObject(this, waitersOffset,//将等待节点加入等待队列
  23. q.next = waiters, q);
  24. else if (timed) {
  25. nanos = deadline - System.nanoTime();
  26. if (nanos <= 0L) {
  27. removeWaiter(q);
  28. return state;
  29. }
  30. LockSupport.parkNanos(this, nanos);//超时等待的方法,到时间就自动唤醒
  31. }
  32. else
  33. LockSupport.park(this);//等待被唤醒
  34. }
  35. }

V report(int s)真正获取结果

  1. private V report(int s) throws ExecutionException {
  2. Object x = outcome;
  3. if (s == NORMAL)
  4. return (V)x;//获取结果
  5. if (s >= CANCELLED)
  6. throw new CancellationException();//取消
  7. throw new ExecutionException((Throwable)x);//执行异常
  8. }

如果执行异常也会获取并抛出