多线程(一)FutureTask简单介绍
一、FutureTask介绍
FutureTask
是一种可以取消的异步的计算任务。它的计算是通过
Callable
实现的,并且有三个状态:等待、运行和完成。完成包括所有计算以任意的方式结束,包括正常结束、取消和异常。
get(): 阻塞等待
get(long timeout, TimeUnit unit): 阻塞特定时间,返回其结果
1.1 FutureTask 的继承机制如下:
public class FutureTask<V> implements RunnableFuture<V> {
/**
* 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.
*
* 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; //任务已中断
……
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
……
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);
}
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
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;
}
1.2 FutureTask的使用如下:
Callable<List> bannerListCallable = () -> adService.queryIndex();
FutureTask<List> bannerTask = new FutureTask<>(bannerListCallable);
executorService.submit(bannerTask);
//Awaits completion or aborts on interrupt or timeout.
entity.put("banner", bannerTask.get()); // 阻塞,等待执行完成返回结果。
版权声明:本文为running_pork原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。