首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java线程池运用简要说明

2013-07-01 
Java线程池使用简要说明鉴于个人经验有限,此文档中可能存在不正确的地方,欢迎各位同学“指指点点”。此文仅做

Java线程池使用简要说明

鉴于个人经验有限,此文档中可能存在不正确的地方,欢迎各位同学“指指点点”。

此文仅做简要介绍,实际应用,会结合Gallery中的实际应用进行总结

相关的源码均在java.util.concurrent.*包下

== 创建线程池 ==

直接介绍下线程池 ThreadPoolExecutor 的用法
??? /**
???? * 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) {...}

* corePollSize????????????????? 核心线程数量
* maximumPoolSize?????????????? 线程池中维护线程的最大数量
* keepAliveTime???????????????? 线程池维护的非核心线程的空闲时间,空闲时间越过此值,就会被关闭
* unit????????????????????????? 线程池维护线程所允许的空闲时间的单位
* workQueue???????????????????? 线程池所使用的缓冲队列
* threadFactory???????????????? 线程池中创建新线程的线程工厂
* handler?????????????????????? 线程池对拒绝任务的处理策略

<br />
=== 系统中的常用实现 ===
在Exectors中,系统提供的几种ThreadPoolExecutor的基本实现
* Executors.newFixedThreadPool
固定大小的线程池,此方法会生成一个corePollSize和maximumPoolSize相同,并且workQueue是使用LinkedBlockingQueue的无界队列的线程池。
它可以保持固定大小的线程数量,并且无界队列可以保证更多的任务也可以正确执行,但若是任务量非常大,则需要占用大量的系统内存。

* Executors.newSingleThreadExecutor
此方法会生成一个corePollSize和maximumPoolSize均为 1 的线程池,它的workQueue是使用LinkedBlockingQueue的无界队列。
它仅会保持一个线程在运行,但有一个无界队列,若是任务少,且不着急,可能考虑这个线程池。

* Executors.newCachedThreadPool
此方法的corePollSize为 0 ,maximumPoolSize的大小为 Integer.MAX_VALUE,它的workQueue使用SynchronousQueue的直接提交队列。
这样的线程池,可以无限的扩大线程容量,也可以在任务量减少时减少线程容量。


还有其它的一些实现,这里就不介绍了,有兴趣的同学可以能过源码深入了解下。


== 任务提交 ==
向线程池提交任务的方法
?? /**
???? * Executes the given task sometime in the future.? The task
???? * may execute in a new thread or in an existing pooled thread.
???? *
???? * If the task cannot be submitted for execution, either because this
???? * executor has been shutdown or because its capacity has been reached,
???? * the task is handled by the current {@code RejectedExecutionHandler}.
???? *
???? * @param command the task to execute
???? * @throws RejectedExecutionException at discretion of
???? *???????? {@code RejectedExecutionHandler}, if the task
???? *???????? cannot be accepted for execution
???? * @throws NullPointerException if {@code command} is null
???? */
??? public void execute(Runnable command) {...}

线程池执行新任务时,会出现四种情况
1. 如果线程池中运行的线程数量少于corePoolSize(核心线程数),则会使用给定的command(Runnable)创建一个新线程
2. 如果线程池中运行的线程数量大于等于corePoolSize,则会将command加入到workQueue(缓冲队列),若成功加入到队列中,则等待执行
3. 如果线程池中运行的线程数量大于等于corePoolSize,而且将command加入到workQueue中失败,则会检查maximumPoolSize(最大线程数量),若总线程数未超过maximumPoolSize,则创建新线程执行此command
4. 如果线程池中运行的线程数量大于等于corePoolSize,将command加入到workQueue中失败,并且总线程数量超过maximumPoolSize,则使用handler(拒绝任务的处理策略)进行处理

== 排队策略 ==
上述情况中出现workQueue增加排队失败的情况,什么时候会成功,什么时候又会失败呢,先来了解下系统提供的三种通用策略

排队有三种通用策略:
* 直接提交:
工作队列的默认选项是 SynchronousQueue,它将任务直接提交给线程而不保持它们。在此,如果不存在可用于立即运行任务的线程,则试图把任务加入队列将失败,因此会构造一个新的线程。此策略可以避免在处理可能具有内部依赖性的请求集时出现锁。直接提交通常要求无界 maximumPoolSizes 以避免拒绝新提交的任务。当命令以超过队列所能处理的平均数连续到达时,此策略允许无界线程具有增长的可能性。<br />
* 无界队列:
使用无界队列(例如,不具有预定义容量的 LinkedBlockingQueue)将导致在所有 corePoolSize 线程都忙时新任务在队列中等待。这样,创建的线程就不会超过 corePoolSize。(因此,maximumPoolSize 的值也就无效了。)当每个任务完全独立于其他任务,即任务执行互不影响时,适合于使用无界队列;例如,在 Web 页服务器中。这种排队可用于处理瞬态突发请求,当命令以超过队列所能处理的平均数连续到达时,此策略允许无界线程具有增长的可能性。
* 有界队列:
当使用有限的 maximumPoolSizes 时,有界队列(如 ArrayBlockingQueue)有助于防止资源耗尽,但是可能较难调整和控制。队列大小和最大池大小可能需要相互折衷:使用大型队列和小型池可以最大限度地降低 CPU 使用率、操作系统资源和上下文切换开销,但是可能导致人工降低吞吐量。如果任务频繁阻塞(例如,如果它们是 I/O 边界),则系统可能为超过您许可的更多线程安排时间。使用小型队列通常要求较大的池大小,CPU 使用率较高,但是可能遇到不可接受的调度开销,这样也会降低吞吐量。

== 线程工厂 ==
threadFactory(创建线程的工厂)常用的为Executors.defaultThreadFactory(),此工厂创建的线程都是非守护线程,纯种的优先级为Thread.NORM_PRIORITY


== 拒绝任务的处理策略 ==
handler(拒绝任务的处理策略)是RejectedExecutionHandler接口的实现,在execute执行新command失败时均会调用此接口的


RejectedExecutionHandler.rejectedExecution(java.lang.Runnable, java.util.concurrent.ThreadPoolExecutor) 方法。
系统提供了4个常用的处理策略:
1. ThreadPoolExecutor.AbortPolicy
此策略是系统的默认策略,处理程序遭到拒绝将抛出运行时 RejectedExecutionException。

2. ThreadPoolExecutor.CallerRunsPolicy
线程调用运行该任务的 execute 本身。此策略提供简单的反馈控制机制,能够减缓新任务的提交速度。

3. ThreadPoolExecutor.DiscardPolicy
不能执行的任务将被删除。

4. ThreadPoolExecutor.DiscardOldestPolicy
如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程)。


热点排行