Executor Framework
Callable VS Runnable
同
1.代表任务,会被线程执行。
不同
1. Callable型的任务能够返回结果或者抛出异常,而Runnable型任务不能
//java.util.concurrent
//Interface Callable<V>
V call() throws Exception
//java.lang
//Interface Runnable
void run()
2.
两个问题
问题1.Thread的target是Runnable类型的,不能直接将Callable型对象作为Thread 的target。
如何将Callable型对象交给Thread?
任务也能够被执行。根据这个需求注意在Executor的子接口ExecutorService中就增加了相关方法submit(Runnable/Callable),submit方法在子类AbstractExecutorService中给出了实现。实现里通过将Runnable/Callable型任务包装成RunnableFuture(继承了Runnable)从而可以交给execute(Runnable command)执行。
问题3:为什么不让FutureTask直接实现Runnable和Future两个接口,而是增加RunnableFuture接口
问题2.call()方法有返回值——但是call方法并不是直接被调用,而是作为线程执行体被调用。
如何获取call()的返回值?
为了解决问题2,JDK1.5中提供了Future接口来代表call()方法的返回值,并提供了一个实现类FutureTask。可以通过
get方法来获得最后执行的结果。
为了解决问题1,让FutureTask实现了Runnable接口,这样可以将 FutureTask交给Thread执行,间接将Callable交给了
Thread。
FutureTask<V>
A cancellable asynchronous computation.
可取消的异步计算
This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation.
The result can only be retrieved when the computation has completed; the get method will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled.
A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable, a FutureTask can be submitted to an Executor for execution.
In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.
Executor接口
ExecutorService接口
AbstractExecutorService抽象类
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Object> ftask = newTaskFor(task, null);
execute(ftask);//ftask是Runnable型
return ftask;//ftask是Future型
}
public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
为什么不让FutureTask直接实现Runnable和Future两个接口,而是增加RunnableFuture接口?
注意submit方法有返回值Future,通过这个Future就可以对。。
ThreadPoolExecutor类
ScheduledExecutorService接口
ScheduledThreadPoolExecutor类