publicinterfaceRunnableFuture<V> extendsRunnable, Future<V> { /** * Sets this Future to the result of its computation * unless it has been cancelled. */ voidrun(); }
/** * Returns {@code true} if this task is periodic. A periodic task may * re-run according to some schedule. A non-periodic task can be * run only once. * * @return {@code true} if this task is periodic */ booleanisPeriodic(); }
publicvoidrun() { // 如果任务状态不对,或者设置当前线程为运行线程失败,就退出 if (state != NEW || !RUNNER.compareAndSet(this, null, Thread.currentThread())) return; try { 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 ints= state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } }
privateintawaitDone(boolean timed, long nanos) throws InterruptedException { // The code below is very delicate, to achieve these goals: // - call nanoTime exactly once for each call to park // - if nanos <= 0L, return promptly without allocation or nanoTime // - if nanos == Long.MIN_VALUE, don't underflow // - if nanos == Long.MAX_VALUE, and nanoTime is non-monotonic // and we suffer a spurious wakeup, we will do no worse than // to park-spin for a while longstartTime=0L; // Special value 0L means not yet parked WaitNodeq=null; booleanqueued=false; // 自旋进行等待 for (;;) { // 完成了,返回状态 ints= state; if (s > COMPLETING) { if (q != null) q.thread = null; return s; } // 等一会 elseif (s == COMPLETING) // We may have already promised (via isDone) that we are done // so never return empty-handed or throw InterruptedException Thread.yield(); // 线程中断了,取消所有等待者 elseif (Thread.interrupted()) { removeWaiter(q); thrownewInterruptedException(); } // 添加新的等待者 elseif (q == null) { if (timed && nanos <= 0L) return s; q = newWaitNode(); } elseif (!queued) queued = WAITERS.weakCompareAndSet(this, q.next = waiters, q); elseif (timed) { finallong parkNanos; if (startTime == 0L) { // first time startTime = System.nanoTime(); if (startTime == 0L) startTime = 1L; parkNanos = nanos; } else { longelapsed= System.nanoTime() - startTime; if (elapsed >= nanos) { removeWaiter(q); return state; } parkNanos = nanos - elapsed; } // 等待 // nanoTime may be slow; recheck before parking if (state < COMPLETING) LockSupport.parkNanos(this, parkNanos); } else LockSupport.park(this); } }