线程池submit任务
提交任务
//线程池的抽象基类
public abstract class AbstractExecutorService implements ExecutorService {
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);//创建一个任务,可以使用实现的Future接口方法来控制任务和获取结果
}
}
//RunnableFuture 实现了Runnable类和Future类,可以提交任务,也可以得到执行结果
public class FutureTask<V> implements RunnableFuture<V> {
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;
private Callable<V> callable;
private Object outcome; // 结果
private volatile Thread runner;
private volatile WaitNode waiters; //等待队列
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW;
}
// Unsafe就是cas的底层实现
private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
private static final long runnerOffset;
private static final long waitersOffset;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = FutureTask.class;
stateOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("state"));
runnerOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("runner"));
waitersOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("waiters"));
} catch (Exception e) {
throw new Error(e);
}
}
}
任务执行
Future.get() 方法等待Runnable.run()执行完成或者被Future.cancel()执行后才能继续执行
这就是场景1的情况
等待线程
public class FutureTask<V> implements RunnableFuture<V> {
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING) //完成标志未设置
s = awaitDone(false, 0L);
return report(s);
}
//等待工作线程结束
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) //正在结束,这个状态设置是在设置结果之前
Thread.yield(); //让出时间片,等待设置结果完成
else if (q == null)
q = new WaitNode();
else if (!queued) //完成状态未设置 && 没有添加到等待队列
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);//这里先设置原来的等待队列头节点作为新节点的后置节点,然后在cas,这就保证了两个操作的原子性
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);//完成状态未设置 && 添加到等待队列
}
}
//报告结果
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x; //1.正常结束
if (s >= CANCELLED)
throw new CancellationException(); //2.被取消
throw new ExecutionException((Throwable)x); //3.任务异常
}
}
工作线程
- Runnable.run()
public class FutureTask<V> implements RunnableFuture<V> {
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 = null;
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);//处理执行cancel(true)的情况,需要等待cancel方法执行完
}
}
private void handlePossibleCancellationInterrupt(int s) {
if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield(); //让出时间片,等待中断完成(这是是担心interupt方法调用之前线程就已经结束了)
}
//设置结果
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {//cas设置状态为COMPLETING
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); //正常设置状态NORMAL,前面cas已经确保了不会被其他线程修改了,所以不需要cas了
finishCompletion();// 清空等待队列 && 唤醒每一个线程
}
}
//设置异常
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); //设置玩完成标志为EXCEPTIONAL
finishCompletion();// 清空等待队列 && 唤醒每一个线程
}
}
// 清空等待队列 && 唤醒每一个线程
private void finishCompletion() {
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { //清空等待队列,CAS设置链表头节点为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;
q = next;
}
break;
}
}
done();
callable = null;
}
}
- Future.cancel()
public class FutureTask<V> implements RunnableFuture<V> {
public boolean cancel(boolean mayInterruptIfRunning) { //参数为true,允许中断线程执行,但设计代码的时候任务代码中必须有可以支持中断的函数,否则也是白搭
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))//cas设置状态为INTERRUPTING||CANCELLED
return false;
try {
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();//中断线程
} finally {
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);//正常设置状态INTERRUPTED,前面cas已经确保了不会被其他线程修改了,所以不需要cas了
}
}
} finally {
finishCompletion();//清空等待队列 && 唤醒每一个线程
}
return true;
}
}
1和2的情况需要对完成标志的修改做访问控制
这就是场景2的类型2的情况
使用UNSAFE.compareAndSwapInt(this, stateOffset, NEW,xxx)来保证只有一个线程能够修改任务状态成功
中断发生有三种情况
- 使用shutdownNow关闭线程池,这个时候Future.get()返回的状态是EXCEPTIONAL
- 调用cancel(true)来中断线程,cancel如果发生在设置结果或者设置异常前面,Future.get()返回状态为INTERRUPTED
- 调用cancel(true)来中断线程,cancel如果发生在设置结果或者设置异常后面,Future.get()返回NORMAL或EXCEPTIONAL