先介绍几个常见类 Runnable、Callable、Future、RunnableFuture、Thread 等。
参考 [Thread 类源码阅读] (https://www.jianshu.com/p/543d2bc5f54a) 中的构造函数,可知 Java 创建线程的方法有两种。
第一种: 继承 Thread 类,重写 run 方法;
第二种:继承 Runable 接口, 重写 run 方法,并作为 Thread 类的构造参数。
代码分别如下:
// 继承 Thread 类,重写 run 方法
new Thread() {
@Override
public void run() {
System.out.println("继承 thread 类子线程运行");
}
}.start();
// 继承 Runable 接口, 重写 run 方法,并作为 Thread 类的构造参数;
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("runable 子线程运行");
}
}).start();
但是在学习 Java 线程相关支持时,还经常看到另外一种方法,使用 Callable 接口, 并且这种方式可以有返回值。
先看代码
FutureTask futureTaskCallable = new FutureTask<>(new Callable() {
@Override
public Integer call() throws Exception {
return 1;
}
});
new Thread(futureTaskCallable).start();
System.out.println("futureTaskCallable 子线程运行结果:" + futureTaskCallable.get());
明明 Thread 类能接收的参数类型就是 Runable 接口对象,怎么就冒出来一个 FutureTask。
现在开始看看 FutureTask 代码结构。
/**
* A cancellable asynchronous computation. This class provides a base
* implementation of {@link Future}, with methods to start and cancel
* a computation, query to see if the computation is complete, and
* retrieve the result of the computation. The result can only be
* retrieved when the computation has completed; the {@code get}
* methods will block if the computation has not yet completed. Once
* the computation has completed, the computation cannot be restarted
* or cancelled (unless the computation is invoked using
* {@link #runAndReset}).
* 可取消的异步计算。
* 这个类提供了 Future 的基本实现,包括启动和取消计算,查查看计算是否完成以及取回计算结果的方法。
* 结果仅当计算完成的情况下才可返回,如果计算未完成 get 方法会被阻塞。
*一旦计算完成,计算就不可以被重启或者取消,除非计算被 runAndReset 方法执行
*
* A {@code FutureTask} can be used to wrap a {@link Callable} or
* {@link Runnable} object. Because {@code FutureTask} implements
* {@code Runnable}, a {@code FutureTask} can be submitted to an
* {@link Executor} for execution.
* FutureTask 可以用来包装 Callable 或 Runnable 对象, 因为 FutureTask 实现了 Runnable 接口, 所以 FutureTask 可以被submitted 给 Executor 类执行。
*
*
In addition to serving as a standalone class, this class provides
* {@code protected} functionality that may be useful when creating
* customized task classes.
*
* @since 1.5
* @author Doug Lea
* @param The result type returned by this FutureTask's {@code get} methods
*/
public class FutureTask implements RunnableFuture {
}
/**
* A {@link Future} that is {@link Runnable}. Successful execution of
* the {@code run} method causes completion of the {@code Future}
* and allows access to its results.
* 是 Runnable 的 Future。成功执行 run 方法会导致 Future完成并允许访问其结果。
* @see FutureTask
* @see Executor
* @since 1.6
* @author Doug Lea
* @param The result type returned by this Future's {@code get} method
*/
public interface RunnableFuture extends Runnable, Future {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
由代码可已看到如下类结构图。
虽然还不知道 FutureTask 是如何工作的,但是由类图可知,FutureTask 实现了接口 Runnable。所以第三种创建线程的方式,实际上还是第二种。
下面开始逐行死磕 FutureTask 代码。
成员变量
/**
* The run state of this task, initially NEW. The run state
* transitions to a terminal state only in methods set,
* setException, and cancel. During completion, state may take on
* transient values of COMPLETING (while outcome is being set) or
* INTERRUPTING (only while interrupting the runner to satisfy a
* cancel(true)). Transitions from these intermediate to final
* states use cheaper ordered/lazy writes because values are unique
* and cannot be further modified.
* 此任务的运行状态,最初为NEW。
* 运行状态仅在set,setException和cancel方法中转换为终端状态。
* 在完成期间,状态可能会采用COMPLETING(正在设置结果时)或
* INTERRUPTING(仅在中断满足cancel(true)的运行者)的瞬态值。从这些中间状态到最终状态的转换使用成本更低的有序惰性写入,因为值是唯一的,无法进一步修改
*
* Possible state transitions:
* 可能的状态变化路线
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
*/
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;
/** The underlying callable; nulled out after running */
// 包装的 callable, 运行结束后置 null
private Callable callable;
/** The result to return or exception to throw from get() */
// 返回值 或者 get 方法抛出的异常
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
// 执行 callable 的线程, run 方法执行时,会使用cas更新
private volatile Thread runner;
/** Treiber stack of waiting threads */
// 等待线程堆栈
private volatile WaitNode waiters;
构造函数
/**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Callable}.
* 创建一个 FutureTask,它将在运行时执行给定的 Callable。
* @param callable the callable task
* @throws NullPointerException if the callable is null
*/
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
/**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Runnable}, and arrange that {@code get} will return the
* given result on successful completion.
* 创建一个 FutureTask,它将在运行时执行给定的 Runnable,在成功完成后执行 get 返回给定的结果。
* @param runnable the runnable task
* @param result the result to return on successful completion. If
* you don't need a particular result, consider using
* constructions of the form:
* {@code Future> f = new FutureTask(runnable, null)}
* @throws NullPointerException if the runnable is null
*/
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
内部类 WaitNode
/**
* Simple linked list nodes to record waiting threads in a Treiber
* stack. See other classes such as Phaser and SynchronousQueue
* for more detailed explanation.
* 简单栈实现
*/
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
FutureTask 自有逻辑
返回结果 或者 抛出异常方法 report
/**
* 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)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
protected void done() { }
/**
* Sets the result of this future to the given value unless
* this future has already been set or has been cancelled.
* 除非已经设置或取消了否则将此 future 的结果设置为给定值。
* This method is invoked internally by the {@link #run} method
* upon successful completion of the computation.
*
* @param v the value
*/
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
/**
* Causes this future to report an {@link ExecutionException}
* with the given throwable as its cause, unless this future has
* already been set or has been cancelled.
* 除非已经设置或取消了该未来,否则将将结果设置为给定 Throwable
*
*
This method is invoked internally by the {@link #run} method
* upon failure of the computation.
*
* @param t the cause of failure
*/
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
/**
* Ensures that any interrupt from a possible cancel(true) is only
* delivered to a task while in run or runAndReset.
* 确保来自可能的cancel(true)的任何中断仅在运行或runAndReset时才传递给任务。
*/
private void handlePossibleCancellationInterrupt(int s) {
// It is possible for our interrupter to stall before getting a
// chance to interrupt us. Let's spin-wait patiently.
if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt
// assert state == INTERRUPTED;
// We want to clear any interrupt we may have received from
// cancel(true). However, it is permissible to use interrupts
// as an independent mechanism for a task to communicate with
// its caller, and there is no way to clear only the
// cancellation interrupt.
//
// Thread.interrupted();
}
/**
* Removes and signals all waiting threads, invokes done(), and
* nulls out callable.
* 删除并通知所有等待线程,调用 done 方法,并使 callable 无效。
*/
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}
/**
* Awaits completion or aborts on interrupt or timeout.
* 等待完成,或者在中断或超时时中止。
* @param timed true if use timed waits
* @param nanos time to wait, if timed
* @return state upon completion
*/
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);
}
}
/**
* Tries to unlink a timed-out or interrupted wait node to avoid
* accumulating garbage. Internal nodes are simply unspliced
* without CAS since it is harmless if they are traversed anyway
* by releasers. To avoid effects of unsplicing from already
* removed nodes, the list is retraversed in case of an apparent
* race. This is slow when there are a lot of nodes, but we don't
* expect lists to be long enough to outweigh higher-overhead
* schemes.
* 尝试取消链接超时或中断的等待节点,以避免积累垃圾。
* 内部节点在没有CAS的情况下根本不会被拼接,因为如果释放者无论如何都要遍历它们,这是无害的
* 为了避免从已删除的节点取消拆分的影响,在出现明显竞争的情况下会重新遍历该列表。
* 当节点很多时,这很慢,但是我们认为列表足够长。
*/
private void removeWaiter(WaitNode node) {
if (node != null) {
node.thread = null;
retry:
for (;;) { // restart on removeWaiter race
for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
s = q.next;
if (q.thread != null)
pred = q;
else if (pred != null) {
pred.next = s;
if (pred.thread == null) // check for race
continue retry;
}
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
continue retry;
}
break;
}
}
}
继承自 Future 的方法
// 返回 FutureTask 是否取消,判断条件 state >= CANCELLED
public boolean isCancelled() {
return state >= CANCELLED;
}
// 返回 FutureTask 是否结束,判断条件 state != NEW
public boolean isDone() {
return state != NEW;
}
// 取消任务
// 只能取消状态为 NEW 的 FutureTask
public boolean cancel(boolean mayInterruptIfRunning) {
//
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
// 中断执行线程
// finally 执行 finishCompletion
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;
}
/**
* @throws CancellationException {@inheritDoc}
*/
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
/**
* @throws CancellationException {@inheritDoc}
*/
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null)
throw new NullPointerException();
int s = state;
if (s <= COMPLETING &&
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
return report(s);
}
继承 Runable 的方法
run
public void run() {
// 如果 状态不为 NEW 或者 cas更新执行 callable 的线程为当前线程失败,返回
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable c = callable;
// callable 非空 且 状态为NEW,执行callable的 call 方法。
// 执行成功, 更新返回值到结果
// 执行异常,更新异常到结果
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
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
// 执行结束后,如果状态为 INTERRUPTING 或 INTERRUPTED, 处理可能的取消动作和中断
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
/**
* Executes the computation without setting its result, and then
* resets this future to initial state, failing to do so if the
* computation encounters an exception or is cancelled. This is
* designed for use with tasks that intrinsically execute more
* than once.
* 在不设置计算结果的情况下执行计算,然后将此将来状态重置为初始状态,如果计算遇到异常或被取消,则无法执行此操作。
* 它设计用于与内部执行多次的任务。
*
* @return {@code true} if successfully run and reset
*/
protected boolean runAndReset() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return false;
boolean ran = false;
int s = state;
try {
Callable c = callable;
if (c != null && s == NEW) {
try {
c.call(); // don't set result
ran = true;
} catch (Throwable ex) {
setException(ex);
}
}
} 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
s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
return ran && s == NEW;
}