简介
Thread 线程
Runable 无返回值任务
Callable 有返回值任务
Executor 任务执行器, 多线程框架
Future 保存异步执行结果
Thread 与 Runnable
@FunctionalInterface
public interface Runnable {
public abstract void run(); //无返回值
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception; //有返回值
public class Thread implements Runnable {
// Thread中没有callable 以及对callable.call方法的调用
// ? callable.call()在何处被调用
// 在TaskFuture里面调用, 代码见下文
private Runnable target;
@FunctionalInterface
// 函数式接口
Thread t = new Thread(()->{ });
任务(Runnable Callable)执行器(Executor)
// 顶层方法
public interface Executor {
void execute(Runnable command);
public interface ExecutorService extends Executor {
......
<T> Future<T> submit(Callable<T> task);
Future<?> submit(Runnable task);
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks);
// submit 将Runnable Callable 封装成 FutureTask
public abstract class AbstractExecutorService implements ExecutorService {
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
public <T> Future<T> submit(Runnable task, T result) {
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Callable<T> task) {
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
TaskFuture 管理线程,任务
Future 顶级接口
TaskFuture 实现类
package java.util.concurrent;
@author Doug Lea
// Future 管理异步任务
// 获取任务执行结果 取消任务 获取任务状态
public interface Future<V> {
// 取消任务
boolean cancel(boolean mayInterruptIfRunning);
// 询问是否已经取消
boolean isCancelled();
// 是否完成
boolean isDone();
// 阻塞当前线程获取异步结果
V get() throws InterruptedException, ExecutionException;
// RunnableFuture继承了runnable 可供线程调用
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
public class FutureTask<V> implements RunnableFuture<V> {
/*
* Possible state transitions:
* NEW -> COMPLETING -> NORMAL
* NEW -> COMPLETING -> EXCEPTIONAL
* NEW -> CANCELLED
* NEW -> INTERRUPTING -> INTERRUPTED
* NORMAL EXCEPTIONAL INTERRUPTED 完成态
* COMPLETING INTERRUPTING 中间态
* NEW 新建
*/
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; //中断成功
/** ---------------- 变量 --------------- */
private Callable<V> callable;
private Object outcome; // callable返回值或抛出的异常
private volatile Thread runner; // 持有callable的线程
/**
* 假设 FutureTask t,
* 有多条线程调用 t.get();
* 这些线程会阻塞, 然后组成一条等待队列
* 当Task(Runnable Callbale)执行完毕时, 可以轮询唤醒等待链条上的线程
*/
private volatile WaitNode waiters;
public FutureTask(Callable<V> callable) {
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
public boolean isCancelled() {
return state >= CANCELLED;
public boolean isDone() {
//开始运行了
return state != NEW;
public void run() {
if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread()))
return;
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
// callable.call()在runnable中被调用
result = c.call();
// 返回值传入 TaskFuture
set(result);
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
// 结束任务,唤醒阻塞的线程
finishCompletion();
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { //可返回异常
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
private void finishCompletion() { //轮询waiters 唤醒调用Future阻塞方法的线程并移除等待节点
// 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; //help GC
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
// 等待
s = awaitDone(false, 0L);
return report(s);
}
private int awaitDone() {
//阻塞调用 get()的线程
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) // 未完成
Thread.yield(); //休眠 休眠时间依赖于CPU时间片的划分
else if (q == null) // 新建等待节点
q = new WaitNode();
else if (!queued) // 插入等待队列, 插入失败自旋
queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q);
else //s == NEW
LockSupport.park(this); //阻塞调用 get()的线程
}
}
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); } //调用TaskFuture的线程
}
@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);
}