本文由Scarb发表于金甲虫的博客,转载请注明出处

Java 线程池

Executors

Executor

执行者接口

execute(Runnable command)

ExecutorService

继承Executor

包含任务执行器的生命周期

ThreadPoolExecutor

见下

Futures

Future

RunnableFuture

接口,实现了RunnableFuture

FutureTask

类,实现了RunnableFuture
是一个Future也是一个Task,实现RunnableFuture

CompletableFuture

提供管理多个任务的能力
任务组合,每个任务完成之后对结果的处理方式,提供链式写法等

线程池

维护两个集合

  1. 线程: HashSet
  2. 任务: BlockingQueue

ThreadPoolExecutor

普通线程池

建议自定义线程池:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)

RejectedExecutionHandler 拒绝策略

当线程池任务队列满,线程池线程数量达到最大线程数时,执行拒绝策略

Java默认提供4种拒绝策略

  • Abort: 抛异常
  • Discard: 扔掉,不抛异常
  • DiscardOldest: 扔掉排队时间最久的
  • CallerRuns: 调用者线程处理任务
  • 可自定义拒绝策略

ForkJoinPool

  • 分解汇总的任务
  • 用很少的县城可以执行很多的任务
  • CPU密集型