publicclassFutureTestimplementsCallable<Integer> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ @Override public Integer call()throws Exception { System.err.println("start call method..."); Thread.sleep(3000); return1111; }
publicinterfaceRunnableFuture<V> extendsRunnable, Future<V> { /** * Sets this Future to the result of its computation * unless it has been cancelled. */ voidrun(); }
Returns result or throws exception for completed task. 主要是上报异步任务执行的结果或返回任务执行发生的异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/** * Returns result or throws exception for completed task. * * @param s completed state value */ @SuppressWarnings("unchecked") private V report(int s)throws ExecutionException { Object x = outcome; if (s == NORMAL) return (V)x; if (s >= CANCELLED) thrownew CancellationException(); thrownew ExecutionException((Throwable)x); }
publicvoidrun(){ // 如果状态 state 不是 NEW,或者设置 runner 值失败 // 表示有别的线程在此之前调用 run 方法,并成功设置了 runner 值 // 保证了只有一个线程可以运行 try 代码块中的代码。 if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return; //以上state值变更的由CAS操作保证原子性 try { Callable<V> c = callable; //只有c不为null且状态state为NEW的情况 if (c != null && state == NEW) { V result; boolean ran; try { //调用callable的call方法,并获得返回结果 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 int s = state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } }