示例代码:
Callable c = new Callable()
{
@Override
public Integer call() throws Exception
{
System.out.println("running...");
Thread.sleep(2000);
return 215;
}
};
FutureTask task = new FutureTask<>(c);
new Thread(task).start();
try
{
System.out.println("result : "+task.get());
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
}
public interface Callable {
V call() throws Exception;
}
Runnable接口大家都很熟悉,那么这个Future接口提供了什么样的方法呢?
public interface Future {
boolean cancel(boolean mayInterruptIfRunning);//取消Future里面关联的call方法
boolean isCancelled();//任务是否取消
boolean isDone();//任务是否完成
V get() throws InterruptedException, ExecutionException;//获取call方法的结果
V get(long timeout, TimeUnit unit)//设置超时时间,超过此时间未收到结果将抛出异常
throws InterruptedException, ExecutionException, TimeoutException;
}
@Override
public void run() {
if (target != null) {
target.run();
}
}
即判断是否传入了Runnable类型的target,如果有,将会执行Runnable的run方法,这里我们传入的是FutureTask,所以会调用FutureTask类的run方法:
public void run() {
sync.innerRun();
}
void innerRun() {
if (!compareAndSetState(READY, RUNNING))
return;
runner = Thread.currentThread();
if (getState() == RUNNING) { // recheck after setting thread
V result;
try {
result = callable.call();//调用的是callable的call方法
} catch (Throwable ex) {
setException(ex);
return;
}
set(result);
} else {
releaseShared(0); // cancel
}
}
public V get() throws InterruptedException, ExecutionException {
return sync.innerGet();
}
V innerGet() throws InterruptedException, ExecutionException {
acquireSharedInterruptibly(0);
if (getState() == CANCELLED)
throw new CancellationException();
if (exception != null)
throw new ExecutionException(exception);
return result;
}
返回了result变量。