整整 Java 线程池
用官方文档来说,线程池解决了两个问题: 一是在执行大量的异步任务时,因为线程池减少了任务开始前的准备工作,如频繁创建线程,启动线程等工作,提升了性能表现;二是提供了一种绑定资源和管理资源的途径,可以进行一些基础的统计分析,比如已经完成的任务数量等。
ExecutorService
接口,继承自 Executor,通过 execute 方法执行 Runnable 任务。ExecutorService 提供了管理终止异步任务的方法和通过 Future 对象追踪异步任务进度的方法。
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);
}
ExecutorService 可以被关闭,随后不再接受新的任务,资源可以被回收。通过 submit 方法扩展 execute 方法,返回一个 Future 对象用于取消执行或者等待执行完成。可以批量执行任务。
public interface ExecutorService extends Executor {
/**
* 已经提交的任务继续执行,不再接受新的任务
*/
void shutdown();
/**
* 尝试停止正在执行的任务,没有执行的任务不再执行,不再接受新的任务
* 返回没有执行的任务的列表
*/
List<Runnable> shutdownNow();
/**
* 阻塞直到(所有任务完成(shutdown 后)| 超时 | 当前线程被中断)发生其一
* 终止时返回 true,反之返回 false
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* 提交新任务,并返回一个 Future 对象用于获取执行结果信息
*/
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
/**
* 执行给定的任务列表,返回任务结果信息的 Future 列表。可设定超时时间
*/
<T> List<Future<T>> invokeAll(Collection<