在水中行走,和根据一份需求开发软件一样,如果它们都 “冻” 住了,那就容易多了。
前面学习了ThreadPoolExecutor,还学习了大神们提供的预先设置好的三个ThreadPoolExecutor,使得我们能更加方便得使用线程池。
在使用线程池的时候,有一些情况不需要返回返回值,但是也有很大情况要求返回线程执行的结果,比如一个操作是成功还是失败。因此我们需要提交线程到线程池,并且得到返回结果。
先来看下下面三个接口
public interface Runnable {
public abstract void run();
}
大家知道常规创建线程的方式有两种,一种是继承Thread,重写run,另一个是用Thread包装一个Runnable的实现类,注意这两种方式来创建线程都无法获取到线程的返回结果,同样,提交到线程池,如果用返回结果的对象来接受,得到的result自然也是null。
public interface Callable {
V call() throws Exception;
}
Callable的call方法存在返回值,即可以返回线程执行的结果,它通常和线程池一起使用
public interface Future {
//取消线程执行,设置为false,则不允许在线程执行时中断
boolean cancel(boolean mayInterruptIfRunning);
//是否取消成功
boolean isCancelled();
//是否执行成功
boolean isDone();
//阻塞获取执行结果
V get() throws InterruptedException, ExecutionException;
//阻塞超时获取执行结果
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
Future对象就是线程池给出的,允许查看线程执行情况,中断线程,并获取线程返回值的对象。
下面来看一下通过Future获取线程返回结果的案例,注意,要返回结果,那么必须选择入参是Callable的提交方法。
ExecutorService service = Executors.newCachedThreadPool();
Future future = service.submit(new Callable() {
@Override
public String call() throws Exception {
System.out.println("执行成功");
return "success";
}
});
System.out.println("result:"+future.get());
public Future submit(Callable task) {
if (task == null) throw new NullPointerException();
//封装成一个RunnableFuture对象
RunnableFuture ftask = newTaskFor(task);
//执行,最终调用到ftask的run方法
execute(ftask);
return ftask;
}
protected RunnableFuture newTaskFor(Callable callable) {
return new FutureTask(callable);
}
//FutureTask实现了RunnableFuture接口
public class FutureTask implements RunnableFuture{
//构造器传入callable对象,赋值给一个成员变量,并设置state
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
}
//RunnableFuture接口又继承了Runnable,Future,因此他既能执行一个线程,又能得到线程的状态、返回值以及实现中断等
public interface RunnableFuture extends Runnable, Future {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
//这里不太明白的一点是 Runnable里明明有run,为什么这个多此一举在写一遍?
void run();
}
我们得知线程池的execute方法最终调用到传入的Runnable对象的run方法,
这里通过submit封装callable并传入的FutureTask对象也是Runnable的对象,因此,最终会调用到FutureTask的run方法,因此这里需要研究这个run方法
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable 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)
//设置结果 ,这里设置给了outcome,因此FutureTask的get方法必然会去获取outcome
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);
}
}
//赋值完成调用 finishCompletion
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
}
好,下面来看下get,是不是真的如我所料?
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
//当s<=COMPLETING 可以还没有赋值,需要阻塞一会
s = awaitDone(false, 0L);
//返回结果 就是outcome
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;
//如果>COMPLATING,要么就执行完,要么就取消或者异常,到report里面去操作就行了
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
//如果是COMPLETING,说明执行完,正要赋值,让个步就行了
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说事,所以这里也有必要把state的各种状态了解一下。
FutureTask内置一个被volatile修饰的state变量。
按照生命周期的阶段可以分为:
NEW 初始状态
COMPLETING 任务已经执行完(正常或者异常),准备赋值结果
NORMAL 任务已经正常执行完,并已将任务返回值赋值到结果
EXCEPTIONAL 任务执行失败,并将异常赋值到结果
CANCELLED 取消
INTERRUPTING 准备尝试中断执行任务的线程
INTERRUPTED 对执行任务的线程进行中断(未必中断到)
关于FutureTask的弊端,有的博客里写道了,但我还不是很明白,先贴出来记录一下!
https://www.cnblogs.com/micrari/p/7374513.html