Java线程之线程池--接口Executor、ExecutorService

来源:互联网 发布:查中药的软件 编辑:程序博客网 时间:2024/06/01 20:26

Executor

JDK解读:


: An object that executes submitted {@link Runnable} tasks.
描述的自身行为:执行任务(即Runnable对象)
提供的对外接口,任务提交,submit,米有返回值
【注意本身行为和对外接口】

: decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.
解耦:定义协议接口,面向接口
遵照协议 《定义任务》,然后《提交等结果》,不用管如何执行
接受满足协议的任务,然后执行
任务执行:确定执行的线程,处理线程调度等

: The command may execute in a new thread, in a pooled thread, at the discretion of the Executor implementation.
在什么线程里执行,即“如何执行”要考虑的一方面

: An Executor is normally used instead of explicitly creating threads.
取代显示创建线程而用Executor(只需按照接口定义任务,提交等待)

即,上述描述了什么是任务、什么是执行,什么是Executor及其设计意义,

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 <tt>Executor</tt> 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);}

———华丽丽的分割线———

ExecutorService

JDK解读:


: An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
两方面,1管理终止,2追踪任务执行情况

包括运行、关门、终止三个生命阶段
关门阶段(shutdown ):不在接收新任务的提交
终止状态(termination),没有正在执行的任务,没有活跃线程

shutdown(),立即进入关门状态,
处理之前接收的任务,直至全部任务结束,没有正在执行的任务,出于终止状态

shutdownNow(),立即进入关门状态,
处理已经提交的任务:阻止等待执行的任务开始执行,【尝试】拦下正在执行的任务(不一定会成功,此时只能等待执行完成)