在多线程协作场景中,我们可以通过继承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接口,阻塞等待完成