引用自:http://www.importnew.com/17572.html
java创建线程有两种方式:
这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果
。
如果需要获取执行结果,就必须通过
共享变量
或者使用线程通信
的方式来达到效果,这样使用起来就比较麻烦。
而自从Java 1.5开始,就提供了Callable和Future
,通过它们可以在任务执行完毕之后得到任务执行结果。
Runnable
Runnable它是一个接口,在它里面只声明了一个run()
方法:
//java.lang.Runnable
public interface Runnable {
public abstract void run();
}
由于run()方法返回值为void类型,所以在执行完任务之后无法返回任何结果。
Callable
Callable位于java.util.concurrent
包下,它也定义了一个方法call()
,不同的是它是带有返回值
的
//java.util.concurrent.Callable
public interface Callable<V> {
V call() throws Exception;
}
可以看到,这是一个泛型接口,call()函数返回的类型就是传递进来的V类型。
使用Callable
那么怎么使用Callable呢?一般情况下是配合ExecutorService来使用的,在ExecutorService接口中声明了若干个submit方法的重载版本:
Future<?> submit(Runnable task);
<T> Future<T> submit(Runnable task, T result);
<T> Future<T> submit(Callable<T> task);
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果
。必要时可以通过get方法获取执行结果,该方法会阻塞
直到任务返回结果。
Future
public interface Future<V> {
/**
* 用来取消任务
* @param mayInterruptIfRunning 表示是否允许取消正在执行却没有执行完毕的任务
* @return 如果取消任务成功则返回true,如果取消任务失败则返回false
*/
boolean cancel(boolean mayInterruptIfRunning);
/**
* 表示任务是否被取消成功
* @return `任务正常完成`前被取消成功,则返回 true ; 如果任务正常完成了,返回false
*/
boolean isCancelled();
/**
* 任务是否正常完成
* @return
*/
boolean isDone();
/**
* 获取执行结果,阻塞至任务执行完毕才返回
*/
V get() throws InterruptedException, ExecutionException;
/**
* 如果在时间范围内没有执行完成,则返回null
*/
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
RunnableFuture也是位于juc
包下,它继承了Runnable, Future两个接口.
//java.util.concurrent.RunnableFuture
public interface RunnableFuture<V> extends Runnable, Future<V> {
//重写Runnable.run()
void run();
}
结构
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; //中断ing
private static final int INTERRUPTED = 6; //中断
private Callable<V> callable;
}
构造函数
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW;
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW;
}
当入参为Runnable
时,它调用了Executors
的工具类方法:
//java.util.concurrent.Executors
public class Executors {
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, 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;
}
}
}
接口方法impl
public boolean isCancelled() {
return state >= CANCELLED;
}
public boolean isDone() {
return state != NEW;
}
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
//阻塞等待执行完成,并将当前线程添加至 WaitNode waiters;
s = awaitDone(false, 0L);
return report(s);
}
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);
}
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try {
//允许正在执行的任务被中断
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally {
//设置状态为INTERRUPTED
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
//唤醒阻塞等待的线程....
finishCompletion();
}
return true;
}
run()
private Callable<V> callable;
private Object outcome; // 正常返回的结果 or 抛出的异常
private volatile Thread runner; //执行callable的线程
private volatile WaitNode waiters; //阻塞等待的线程s,链表结构
public void run() {
//如果state不为new则直接返回
//如果cas设置runner: null ->当前线程, 若失败则直接返回;
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 {
//执行real任务
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
//1.执行失败,则设置异常以及状态信息
setException(ex);
}
if (ran)
//2.执行成功,设置执行结果;
set(result);
}
} finally {
runner = null;
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
//1.执行失败
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); //
finishCompletion();
}
}
//2.执行成功
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
//唤醒阻塞等待的线程....
finishCompletion();
}
}
定义Callable:
Callable<Integer> callable = () -> {
System.out.println("子线程在进行计算");
Thread.sleep(3000);
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
return sum;
};
Callable+Future
void testCallableFuture() throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
System.out.println("main------开始计算");
//实际上此时Future的具体实现类为: FutureTask
Future<Integer> future = executor.submit(callable);
int result = future.get();
System.out.println("main------计算完成:"+result);
}
Callable+FutureTask ----ThreadPool
void testCallableFutureTask() throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
System.out.println("main------开始计算");
FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
executor.submit(futureTask);
//直接通过futureTask,即可获取结果
int result = futureTask.get();
System.out.println("main------计算完成:"+result);
}
Callable+FutureTask ----Thread
FutureTask还可以脱离线程池使用:
void testCallableFutureTask2() throws ExecutionException, InterruptedException {
System.out.println("main------开始计算");
FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
//直接使用线程
new Thread(futureTask).start();
int result = futureTask.get();
System.out.println("main------计算完成:"+result);
}