一、Callable、Future和FutureTask概述
1、Callable和Runnable的區別
Executor框架使用Runnable作爲其基本的任務表示形式。Runnable是一種侷限性很大的抽象,它沒有返回值並且不能拋出異常
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
許多任務實際上都是存在延遲的計算,對於這些任務,Callable是一種更好的抽象:它會返回一個值,並可能拋出一個異常
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
2、Future
Future表示一個任務的生命週期,並提供了方法來判斷是否已經完成或取消,以及獲取任務的結果和取消任務等
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;
}
cancel方法用於取消任務,取消成功返回true,取消失敗返回false。mayInterruptIfRunning參數含義是是否允許取消正在運行的任務。
isCancelled方法用於判斷任務是否被取消成功,在任務正常結束之前被取消成功則會返回true。
isDone方法用於判斷任務是否已經完成
get用於獲取任務的返回值
get(long timeout, TimeUnit unit) 用來獲取執行結果,如果在指定時間內,還沒獲取到結果,就直接返回null。
綜上所述Future提供了三種功能
1、判斷任務是否完成
2、中斷任務
3、獲取結果
3、FutureTask
Future只是一個接口,無法直接創建對象,因此需要藉助FutureTask來使用
public class FutureTask<V> implements RunnableFuture<V> {}
FutureTask實現了RunnableFuture接口
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
RunnableFuture繼承自Runnable和Future
一個FutureTask 可以用來包裝一個 Callable 或是一個Runnable對象。因爲FurtureTask實現了Runnable方法,所以一個 FutureTask可以提交(submit)給一個Excutor執行(excution). 它同時實現了Callable, 所以也可以作爲Future得到Callable的返回值。
FutureTask有兩個很重要的屬性分別是state和runner
/**
* 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;
這幾種狀態的轉換可能爲
- NEW -> COMPLETING -> NORMAL(正常結束)
- NEW -> COMPLETING -> EXCEPTIONAL(異常結束)
- NEW -> CANCELLED(取消執行)
- NEW-INTERRUPTING-INTERRUPTED(被中斷)
通過幾種成員方法講述下狀態的轉換
1、構造函數
/**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Callable}.
*
* @param callable the callable task
* @throws NullPointerException if the callable is null
*/
public FutureTask(Callable<V> 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.
*
* @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<Void>(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
}
可以看到任務被創建時的初始狀態是NEW,構造函數有2種重載函數,一種接收Runnable,一種接收Callable,接收Runnable的時候會進行將Runnable轉爲Callable。如下
/**
* Returns a {@link Callable} object that, when
* called, runs the given task and returns the given result. This
* can be useful when applying methods requiring a
* {@code Callable} to an otherwise resultless action.
* @param task the task to run
* @param result the result to return
* @param <T> the type of the result
* @return a callable object
* @throws NullPointerException if task null
*/
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
/**
* A callable that runs given task and returns given result
*/
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
可以看到就是讓傳入的參數作爲call的返回值。使用call方法來調用run方法即可。把傳入的 T result 作爲callable的返回結果
啓動任務
當創建完一個Task通常會提交給Executors來執行,當然也可以使用Thread來執行,Thread的start()方法會調用Task的run()方法。看下FutureTask的run()方法的實現:
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 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);
}
}
首先判斷任務是否處於NEW的狀態,如果不是則直接返回。因爲任務在初始化完成之前可能就直接被cancel,這時任務已經不處於NEW狀態,可能處於Interrupting狀態,這也是任務沒完全啓動,取消時任務一直得不到啓動的原因。
如果是處於NEW狀態,則判斷task的線程是否爲null,如果不爲null,說明已經有線程在運行了,直接返回。如果爲null,則將當前線程賦值給task的線程。此處使用CAS是爲了保證對work Thread的賦值是原子性操作。保證多個線程對task進行提交的時候,run只被調用一次。
接下來任務不爲null,並且任務處於NEW狀態就啓動。正常執行就set結果,否則就setException。最後把work Thread設置爲null。
set方法
/**
* Sets the result of this future to the given value unless
* this future has already been set or has been cancelled.
*
* <p>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();
}
}
可以看到,如果task處於NEW,則付值爲COMPLETING,再將結果設置到outcome中,再將任務設置成NORMAL狀態。
整個狀態的流轉就是上面提到的:- NEW -> COMPLETING -> NORMAL(正常結束)
最後調用finishCompletion()方法
/**
* Removes and signals all waiting threads, invokes done(), and
* nulls out 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
}
```java
可以看到主要任務是喚醒等待在task上的所有線程,WaitNode存放的是所有調用get方法阻塞在該task上的線程。
調用done方法;將task的任務設置成null。至此結束整個run的流程。
接下來看下get方法
```java
/**
* @throws CancellationException {@inheritDoc}
*/
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
可以看到,第一步是判斷任務的狀態是否是完成狀態,如果是完成狀態,則調用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);
}
如果任務狀態NORMAL,則表示任務正常結束,已經設置了返回值,直接返回。如果任務是取消或者中斷則表示任務異常,則拋出異常。
如果get時,FutureTask的狀態爲未完成狀態,則調用awaitDone方法進行阻塞。awaitDone():
/**
* 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);
}
}
awaitDone可以看作是輪詢查詢status的變化,在get阻塞的期間
1、如果調用get的線程被中斷,則移除所有阻塞在等待隊列上的線程,並拋出InterruptedException異常。
2、如果status表示任務已經完成(正常完成、被取消)直接返回任務狀態
3、如果任務正在執行,證明此時正在set結果,讓線程等待下。
4、如果線程是NEW狀態,將該線程加入到等待隊列當中
5、如果get未設置超時時間,則讓線程繼續阻塞
6、設置了超時時間檢查時間是否已到,到了的話移除所有的等待線程,並返回當前的任務status,沒到的話繼續等待。
四、舉例說明Callable、Future和FutureTask框架的使用
package cn.enjoy.controller.thread;
import cn.enjoy.controller.thread.DBPOLL.SleepTools;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* @author:wangle
* @description:
* @version:V1.0
* @date:2020-03-23 21:55
**/
public class CallableFutureFutureTask {
private static class UseCallable implements Callable<Integer> {
@Override
public Integer call()throws Exception{
Integer i =0;
System.out.println("Callable開始計算");
for( i=0;i<100000;i++){
System.out.println("run");
System.out.println(Thread.currentThread().isInterrupted());
if(Thread.currentThread().isInterrupted()){
System.out.println("線程被中斷");
break;
}
}
System.out.println("線程done");
return i;
}
}
public static void main(String[] args)throws Exception{
UseCallable useCallable = new UseCallable();
FutureTask<Integer> futureTask = new FutureTask<Integer>(useCallable);
Thread testThread = new Thread(futureTask);
testThread.start();
Thread.sleep(1000);
futureTask.cancel(true);
System.out.println(futureTask.get());
SleepTools.second(2);
}
}
1、cancel後,任務直接被終止結束,因爲我在線程中進行捕獲了中斷進行了處理,如果不進行處理則不會被中斷,感興趣的可以試試。(因爲java的線程是協作的,並非是搶佔的)
2、調用get方法後會一直阻塞到任務執行完成。
注
本文源碼來自JDK1.8,1.6是使用AQS實現