一.介绍
Executor是java5之后引进的,java5之前的Thread既包含了异步的工作任务又有执行机制,而且Thread创建线程缺乏统一的管理,缺乏更更多的功能(定时执行,定期执行,线程中断)。Executor框架可以用来控制线程的启动,执行和关闭,负责执行机制,而把异步任务分离出来,更易7管理效率更好,最关键的一点是可以避免this逃逸问题。
public class ThisEscape {
public ThisEscape() {
new Thread(new EscapeRunable()).start();
}
private class EscapeRunable implents Runnable
{
@Override
public void run(){
//内部类会自动持有外部类(ThisEscape)的this引用,
所以外部类对象可能还为构造完成发生了this指针逃逸}
}
}Executor 框架包括:工作任务,执行机制,和异步计算结果。
- 工作任务:Runnable和Callable接口。
- 执行机制:Executor接口,ExecuorService接口,Executors接口
- 异步计算结果: Future接口
二.执行机制
- Executor,ExecuorService,Executors接口
JDK8中Excutor的实现:
public interface Executor {
/**
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the {@code Executor} implementation.
*
* @param command the runnable task
* @throws RejectedExecutionException if this task cannot be
* accepted for execution
* @throws NullPointerException if command is null
*/
void execute(Runnable command);
} Executor接口中只定义了一个方法executer,接收一个Runnable实例,用来执行一个任务。
2.ExecutorService 接口继承自 Executor 接口,它提供了更丰富的实现多线程的方法。
public interface ExecutorService extends Executor {
//不会立即关闭实例,而是等所有提交任务完成后关闭,期间不接受新task
void shutdown();
//尝试立即销毁实例,终止正在执行的任务,返回等待执行的任务
List<Runnable> shutdownNow();
//当前线程阻塞,直到在timout时间内完成所有task。如果实例在时间内成功关闭返回false,否则返回true。
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
//提交一个Callable对象,返回结果Future对象
<T> Future<T> submit(Callable<T> task);
//task完成后返回指定结果当result。
<T> Future<T> submit(Runnable task, T result);
//提交一个Runnable对象,返回一个Future对象,如果对象为空,则任务执行完成
Future<?> submit(Runnable task);
//提交任务集合,返回所有任务当执行结果Future对象list。
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException;
//提交任务集合,返回所有任务,返回任意一个result。
<T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException}3.Executors
Executors类提供了便利的工厂方法来创建不同类型的ExecutorServices。
public static ExecutorService newFixedThreadPool(int nThreads)
创建固定数目线程的线程池。
public static ExecutorService newCachedThreadPool()
创建一个可缓存的线程池,调用execute将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线 程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
public static ExecutorService newSingleThreadExecutor()
创建一个单线程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。