线程池整个体系中涉及到三个和线程有关的接口和一个和线程池有关的接口。
public interface Executor { void execute(Runnable command); }
线程池中最顶层的接口,只有一个方法。execute方法接受Runnable类型的task并在未来的某个时刻执行task,执行task有可能用线程池里的线程也有可能用新建的线程。
Future接口是Java世界中所有异步执行结果的占位符的顶层接口,不仅仅在线程池中在Netty中也有广泛的应用。对于一个异步的方法,方法调用会立即返回,无论方法是否执行完毕,所以需要Future作为方法结果的占位符,并借助Future获得异步方法是否执行完毕以及在执行完毕的时候获得结果,以及取消异步方法的执行。
public interface Future<V> { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
老朋友了,没啥好说的
public interface Runnable { public abstract void run(); }
新面孔,和Runnable类似都是用来在新建线程的时候使用
public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
在线程池中真正使用到的一个类,注意这是一个实现了Future接口的类而非接口,间接的实现了Callable和Future接口。它的作用主要有
每一个FutureTask对象都代表一个submit的task,因为FutureTask在执行的过程中可能会发生很多变化,如执行完毕,异常退出,被cancel等,所以需要一个state来存储FutureTask在执行过程中的状态变化。该state是volatile的,所以对state的修改肯定是CAS的。
private volatile int state; private static final int NEW = 0; private static final int COMPLETING = 1; private static final int NORMAL = 2; private static final int EXCEPTIONAL = 3; private static final int CANCELLED = 4; private static final int INTERRUPTING = 5; private static final int INTERRUPTED = 6;
而且这些state的所有可能取值都是int的,所以可以通过比较大小的方式来确定FutureTask的执行状态。
执行FutureTask中的任务,把任务的结果放到outcome中。
public void run() { 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 { 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); } }
如果FutureTask的state<= COMPLETING,说明FutureTask还未执行完毕,调用get方法的线程应该阻塞并等待,否则调用report返回结果。
public V get() throws InterruptedException, ExecutionException { int s = state; if (s <= COMPLETING) s = awaitDone(false, 0L); return report(s); }
阻塞调用get方法的线程和AQS阻塞线程思路类似,维护一个队列,线程被阻塞的时候创建Node加入队列,然后park当前线程。
private int awaitDone(boolean timed, long nanos) throws InterruptedException { final long deadline = timed ? System.nanoTime() + nanos : 0L; WaitNode q = null; boolean queued = false; for (;;) { if (Thread.interrupted()) { removeWaiter(q); throw new InterruptedException(); } int s = state; if (s > COMPLETING) { if (q != null) q.thread = null; return s; } else if (s == COMPLETING) // cannot time out yet Thread.yield(); else if (q == null) q = new WaitNode(); else if (!queued) queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q); else if (timed) { nanos = deadline - System.nanoTime(); if (nanos <= 0L) { removeWaiter(q); return state; } LockSupport.parkNanos(this, nanos); } else LockSupport.park(this); } }
如果state>=COMPLETING,说明FutureTask执行完毕,可以直接返回结果。其实就是吧outcome方法强转一下。
private V report(int s) throws ExecutionException { Object x = outcome; if (s == NORMAL) return (V)x; if (s >= CANCELLED) throw new CancellationException(); throw new ExecutionException((Throwable)x); }
public boolean cancel(boolean mayInterruptIfRunning) { if (!(state == NEW && UNSAFE.compareAndSwapInt(this, stateOffset, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED))) return false; try { // in case call to interrupt throws exception if (mayInterruptIfRunning) { try { Thread t = runner; if (t != null) t.interrupt(); } finally { // final state UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); } } } finally { finishCompletion(); } return true; }
原文:https://www.cnblogs.com/AshOfTime/p/10963133.html