在多線程協作場景中,我們可以通過繼承Thread或者實現Runnable接口。但是,Runnable接口並沒有返回值,如果我們需要之前的執行結果,發現沒轍了;這個時候出現了Callable和Future,通過實現Callable接口得到執行結果;通過Future獲取、監視、控制執行結果。
1.Callable和Runnable的區別
通過源碼我們一起看下,Callable接口:
package java.util.concurrent;
/**
* <p>The {@code Callable} interface is similar to {@link
* java.lang.Runnable}, in that both are designed for classes whose
* instances are potentially executed by another thread. A
* {@code Runnable}, however, does not return a result and cannot
* throw a checked exception.
*/
@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;
翻譯如下,Callable接口和Runable接口是相似的,兩個接口的實例被設計通過其他線程執行。但是Runnable接口沒有返回結果並且不能拋出一個已檢查的異常。其中V call() throws Exception方法,V是我們執行的返回結果的類型,啓動線程就會執行這個方法
Runnable接口:
package java.lang;
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
可以看到沒有返回結果。
2.Future類結構圖
我們直接引用官網給出的
官網給出的一個簡單的用法
interface ArchiveSearcher { String search(String target); }
class App {
ExecutorService executor = ...
ArchiveSearcher searcher = ...
void showSearch(final String target) throws InterruptedException {
Future<String> future = executor.submit(new Callable<String>() {
public String call() {
return searcher.search(target);
}
});
displayOtherThings(); // do other things while searching
try {
displayText(future.get()); // use future
} catch (ExecutionException ex) { cleanup(); return; }
}
}
2.1看下Future的源碼
Future接口:
package java.util.concurrent;
public interface Future<V> {
/**
* Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, has already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when {@code cancel} is called,
* this task should never run. If the task has already started,
* then the {@code mayInterruptIfRunning} parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* Returns {@code true} if this task was cancelled before it completed
* normally.
*/
boolean isCancelled();
/**
* Completion may be due to normal termination, an exception, or
* cancellation -- in all of these cases, this method will return
* {@code true}.
*/
boolean isDone();
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*/
V get() throws InterruptedException, ExecutionException;
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
boolean cancel(boolean mayInterruptIfRunning):嘗試取消任務的執行,如果任務已經執行完成或者已經被取消或者因爲某些原因不能被取消,嘗試將失敗。如果任務沒有開始,調用了cancel會取消成功。如果任務已經開始,參數mayInterruptIfRunning,true表示,不管任務正在執行,都會去嘗試停止任務。
boolean isCancelled();如果任務在完成之前被取消返回ture
boolean isDone();正常終止,異常終止,取消都會返回true
V get() throws InterruptedException, ExecutionException;一直阻塞,等待計算完成,返回結果
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;阻塞指定時長,等待計算完成返回結果,如果超時,返回TimeoutException
2.2FutureTask實例和源碼解析
import java.util.concurrent.*;
/**
* @author zisong yue
* @date 2018-11-26
* @description 在玩英雄聯盟中,假設閃現和引燃技能都釋放完成,才能將對方英雄擊殺。
*/
public class FutureTaskTest {
Callable<String> shanxian = new Callable<String>() {
@Override
public String call() throws Exception {
for (int i = 0; i < 2; i++) {
System.out.println("閃現技能釋放中......");
Thread.sleep(2000);
}
return "閃現技能釋放完成";
}
};
Callable<String> yinran = new Callable<String>() {
@Override
public String call() throws Exception {
for (int i = 0; i < 4; i++) {
System.out.println("引燃技能釋放中......");
Thread.sleep(2000);
}
return "引燃技能釋放完成";
}
};
public static void main(String[] args) {
FutureTaskTest futureTaskTest = new FutureTaskTest();
ExecutorService es = Executors.newCachedThreadPool();
FutureTask shanxianTask = new FutureTask<String>(futureTaskTest.shanxian);
FutureTask yinranTask = new FutureTask<String>(futureTaskTest.yinran);
es.submit(shanxianTask);
es.submit(yinranTask);
try {
System.out.println(shanxianTask.get());//一直阻塞直到任務完成,即FutureTask中state爲normal
System.out.println(yinranTask.get());//一直阻塞直到任務完成,即FutureTask中state爲normal
System.out.println("擊殺對方英雄!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
測試結果:
FutureTask源碼解析
package java.util.concurrent;
import java.util.concurrent.locks.LockSupport;
public class FutureTask<V> implements RunnableFuture<V> {
/**
* 狀態轉換:
* 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;
/** The underlying callable; nulled out after running */
private Callable<V> callable;
/** The result to return or exception to throw from get() */
private Object outcome;
/** The thread running the callable; CASed during run() */
private volatile Thread runner;
/** Treiber stack of waiting threads */
private volatile WaitNode waiters;
/**
* Returns result or throws exception for completed task.
*/
@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);
}
/**
* Creates a {@code FutureTask} that will, upon running, execute the
* given {@code Callable}.
*/
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.
*/
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
public boolean isCancelled() {
return state >= CANCELLED;
}
public boolean isDone() {
return state != NEW;
}
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
/**
* @throws CancellationException {@inheritDoc}
*/
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);
}
/**
* Sets the result of this future to the given value unless
* this future has already been set or has been cancelled.
*/
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
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);
}
}
/**
* Simple linked list nodes to record waiting threads in a Treiber
* stack. See other classes such as Phaser and SynchronousQueue
* for more detailed explanation.
*/
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
/**
* Awaits completion or aborts on interrupt or timeout.
*/
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);
}
}
}
FutureTask 實現了RunnableFuture接口,RunnableFuture接口集成了Runnable和Future接口。new FutureTask執行裏面的方法run(),run()方法中調用callable的call()方法,得到返回值result,調用set(result)將結果賦值給outcome變量;調用FutureTask的get()方法,get()方法中先判斷任務狀態,如果小於completing,調用awitdone接口,阻塞等待完成