publicvoidrun(){ 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 { //拿到结果设置ran为true result = c.call(); ran = true; } catch (Throwable ex) { //异常设置结果为空ran为false并设置异常 result = null; ran = false; setException(ex); } //ran为true时放入结果 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); } }
1 2 3 4 5 6 7
public V get()throws InterruptedException, ExecutionException { int s = state; //会一直挂起知道处理业务的线程完成,唤醒等待线程 if (s <= COMPLETING) s = awaitDone(false, 0L); return report(s); }
int s = state; if (s > COMPLETING) { if (q != null) q.thread = null; return s; } elseif (s == COMPLETING) // cannot time out yet Thread.yield(); elseif (q == null) q = new WaitNode(); elseif (!queued) queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q); elseif (timed) { nanos = deadline - System.nanoTime(); if (nanos <= 0L) { removeWaiter(q); return state; } LockSupport.parkNanos(this, nanos); } else LockSupport.park(this); } }
带有超时时间的get,到达时间后,会判断线程状态,如果未完成,抛出超时异常。
1 2 3 4 5 6 7 8 9 10
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (unit == null) thrownew NullPointerException(); int s = state; if (s <= COMPLETING && (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING) thrownew TimeoutException(); return report(s); }