Most visited

Recently visited

Added in API level 1

ThreadPoolExecutor

public class ThreadPoolExecutor
extends AbstractExecutorService

java.lang.Object
   ↳ java.util.concurrent.AbstractExecutorService
     ↳ java.util.concurrent.ThreadPoolExecutor
Known Direct Subclasses


ExecutorService使用 Executors工厂方法使用可能的几个池线程中的一个来执行每个提交的任务。

线程池解决了两个不同的问题:由于减少了每个任务的调用开销,它们通常在执行大量异步任务时提供改进的性能,并且它们提供了一种限制和管理资源(包括线程)的方法,在执行任务。 每个ThreadPoolExecutor还保留一些基本的统计数据,例如完成的任务数量。

为了在广泛的上下文中有用,此类提供了许多可调参数和可扩展性钩子。 但是,我们建议程序员使用更方便的Executors工厂方法newCachedThreadPool() (无界线程池,自动线程回收), newFixedThreadPool(int) (固定大小的线程池)和newSingleThreadExecutor() (单个后台线程),它们为最常见的使用场景预配置设置。 否则,请在手动配置和调整此类时使用以下指南:

Core and maximum pool sizes
A ThreadPoolExecutor will automatically adjust the pool size (see getPoolSize()) according to the bounds set by corePoolSize (see getCorePoolSize()) and maximumPoolSize (see getMaximumPoolSize()). When a new task is submitted in method execute(Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full. By setting corePoolSize and maximumPoolSize the same, you create a fixed-size thread pool. By setting maximumPoolSize to an essentially unbounded value such as Integer.MAX_VALUE, you allow the pool to accommodate an arbitrary number of concurrent tasks. Most typically, core and maximum pool sizes are set only upon construction, but they may also be changed dynamically using setCorePoolSize(int) and setMaximumPoolSize(int).
On-demand construction
By default, even core threads are initially created and started only when new tasks arrive, but this can be overridden dynamically using method prestartCoreThread() or prestartAllCoreThreads(). You probably want to prestart threads if you construct the pool with a non-empty queue.
Creating new threads
New threads are created using a ThreadFactory. If not otherwise specified, a defaultThreadFactory() is used, that creates threads to all be in the same ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc. If a ThreadFactory fails to create a thread when asked by returning null from newThread, the executor will continue, but might not be able to execute any tasks. Threads should possess the "modifyThread" RuntimePermission. If worker threads or other threads using the pool do not possess this permission, service may be degraded: configuration changes may not take effect in a timely manner, and a shutdown pool may remain in a state in which termination is possible but not completed.
Keep-alive times
If the pool currently has more than corePoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime (see getKeepAliveTime(TimeUnit)). This provides a means of reducing resource consumption when the pool is not being actively used. If the pool becomes more active later, new threads will be constructed. This parameter can also be changed dynamically using method setKeepAliveTime(long, TimeUnit). Using a value of Long.MAX_VALUE NANOSECONDS effectively disables idle threads from ever terminating prior to shut down. By default, the keep-alive policy applies only when there are more than corePoolSize threads, but method allowCoreThreadTimeOut(boolean) can be used to apply this time-out policy to core threads as well, so long as the keepAliveTime value is non-zero.
Queuing
Any BlockingQueue may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:
  • If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.
  • If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.
  • If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.
There are three general strategies for queuing:
  1. Direct handoffs. A good default choice for a work queue is a SynchronousQueue that hands off tasks to threads without otherwise holding them. Here, an attempt to queue a task will fail if no threads are immediately available to run it, so a new thread will be constructed. This policy avoids lockups when handling sets of requests that might have internal dependencies. Direct handoffs generally require unbounded maximumPoolSizes to avoid rejection of new submitted tasks. This in turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than they can be processed.
  2. Unbounded queues. Using an unbounded queue (for example a LinkedBlockingQueue without a predefined capacity) will cause new tasks to wait in the queue when all corePoolSize threads are busy. Thus, no more than corePoolSize threads will ever be created. (And the value of the maximumPoolSize therefore doesn't have any effect.) This may be appropriate when each task is completely independent of others, so tasks cannot affect each others execution; for example, in a web page server. While this style of queuing can be useful in smoothing out transient bursts of requests, it admits the possibility of unbounded work queue growth when commands continue to arrive on average faster than they can be processed.
  3. Bounded queues. A bounded queue (for example, an ArrayBlockingQueue) helps prevent resource exhaustion when used with finite maximumPoolSizes, but can be more difficult to tune and control. Queue sizes and maximum pool sizes may be traded off for each other: Using large queues and small pools minimizes CPU usage, OS resources, and context-switching overhead, but can lead to artificially low throughput. If tasks frequently block (for example if they are I/O bound), a system may be able to schedule time for more threads than you otherwise allow. Use of small queues generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases throughput.
Rejected tasks
New tasks submitted in method execute(Runnable) will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated. In either case, the execute method invokes the rejectedExecution(Runnable, ThreadPoolExecutor) method of its RejectedExecutionHandler. Four predefined handler policies are provided:
  1. In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.
  2. In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.
  3. In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.
  4. In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)
It is possible to define and use other kinds of RejectedExecutionHandler classes. Doing so requires some care especially when policies are designed to work only under particular capacity or queuing policies.
Hook methods
This class provides protected overridable beforeExecute(Thread, Runnable) and afterExecute(Runnable, Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated.

如果hook,callback或BlockingQueue方法抛出异常,则内部工作线程可能会失败,突然终止并可能被替换。

Queue maintenance
Method getQueue() allows access to the work queue for purposes of monitoring and debugging. Use of this method for any other purpose is strongly discouraged. Two supplied methods, remove(Runnable) and purge() are available to assist in storage reclamation when large numbers of queued tasks become cancelled.
Finalization
A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically. If you would like to ensure that unreferenced pools are reclaimed even if users forget to call shutdown(), then you must arrange that unused threads eventually die, by setting appropriate keep-alive times, using a lower bound of zero core threads and/or setting allowCoreThreadTimeOut(boolean).

扩展示例 该类的大多数扩展都会覆盖一个或多个受保护的挂钩方法。 例如,以下是添加简单暂停/恢复功能的子类:

 class PausableThreadPoolExecutor extends ThreadPoolExecutor {
   private boolean isPaused;
   private ReentrantLock pauseLock = new ReentrantLock();
   private Condition unpaused = pauseLock.newCondition();

   public PausableThreadPoolExecutor(...) { super(...); }

   protected void beforeExecute(Thread t, Runnable r) {
     super.beforeExecute(t, r);
     pauseLock.lock();
     try {
       while (isPaused) unpaused.await();
     } catch (InterruptedException ie) {
       t.interrupt();
     } finally {
       pauseLock.unlock();
     }
   }

   public void pause() {
     pauseLock.lock();
     try {
       isPaused = true;
     } finally {
       pauseLock.unlock();
     }
   }

   public void resume() {
     pauseLock.lock();
     try {
       isPaused = false;
       unpaused.signalAll();
     } finally {
       pauseLock.unlock();
     }
   }
 }

Summary

Nested classes

class ThreadPoolExecutor.AbortPolicy

拒绝任务的处理程序,抛出RejectedExecutionException

class ThreadPoolExecutor.CallerRunsPolicy

被拒绝任务的处理程序直接在execute方法的调用线程中运行被拒绝的任务,除非执行程序已关闭,在这种情况下任务将被丢弃。

class ThreadPoolExecutor.DiscardOldestPolicy

拒绝任务的处理程序,丢弃最旧的未处理的请求,然后重试execute ,除非执行程序关闭,在这种情况下任务将被丢弃。

class ThreadPoolExecutor.DiscardPolicy

被拒绝任务的处理程序,默默丢弃被拒绝的任务。

Public constructors

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)

用给定的初始参数和默认线程工厂和被拒绝的执行处理程序创建一个新的 ThreadPoolExecutor

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)

用给定的初始参数和默认拒绝执行处理程序创建一个新的 ThreadPoolExecutor

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)

用给定的初始参数和默认线程工厂创建一个新的 ThreadPoolExecutor

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)

用给定的初始参数创建一个新的 ThreadPoolExecutor

Public methods

void allowCoreThreadTimeOut(boolean value)

设置策略来管理核心线程是否可能超时并在保持活动时间内没有任何任务到达时终止,当新任务到达时如果需要则替换。

boolean allowsCoreThreadTimeOut()

如果此池允许核心线程超时并在keepAlive时间内没有任何任务到达时终止,则返回true;如果新任务到达时需要替换,则返回true。

boolean awaitTermination(long timeout, TimeUnit unit)
void execute(Runnable command)

将来执行给定的任务。

int getActiveCount()

返回正在执行任务的线程的近似数量。

long getCompletedTaskCount()

返回已完成执行的大约总任务数。

int getCorePoolSize()

返回线程的核心数量。

long getKeepAliveTime(TimeUnit unit)

返回线程保持活动时间,这是线程在终止之前可能保持空闲的时间量。

int getLargestPoolSize()

返回池中同时存在的最大线程数。

int getMaximumPoolSize()

返回允许的最大线程数。

int getPoolSize()

返回池中的当前线程数。

BlockingQueue<Runnable> getQueue()

返回此执行程序使用的任务队列。

RejectedExecutionHandler getRejectedExecutionHandler()

返回不可执行任务的当前处理程序。

long getTaskCount()

返回曾经计划执行的任务的近似总数。

ThreadFactory getThreadFactory()

返回用于创建新线程的线程工厂。

boolean isShutdown()
boolean isTerminated()
boolean isTerminating()

如果此执行程序正在 shutdown()shutdownNow()之后终止,但尚未完全终止,则返回true。

int prestartAllCoreThreads()

启动所有核心线程,导致它们空闲地等待工作。

boolean prestartCoreThread()

启动一个核心线程,导致它闲置地等待工作。

void purge()

尝试从工作队列中删除已取消的所有 Future任务。

boolean remove(Runnable task)

如果该任务存在,则从执行程序的内部队列中删除此任务,从而导致它在尚未启动的情况下不会运行。

void setCorePoolSize(int corePoolSize)

设置线程的核心数量。

void setKeepAliveTime(long time, TimeUnit unit)

设置线程保持活动时间,这是线程在终止之前可能保持空闲的时间量。

void setMaximumPoolSize(int maximumPoolSize)

设置允许的最大线程数。

void setRejectedExecutionHandler(RejectedExecutionHandler handler)

为不可执行的任务设置新的处理程序。

void setThreadFactory(ThreadFactory threadFactory)

设置用于创建新线程的线程工厂。

void shutdown()

启动先前提交的任务执行的有序关闭,但不会接受新任务。

List<Runnable> shutdownNow()

尝试停止所有正在执行的任务,暂停等待任务的处理,并返回正在等待执行的任务列表。

String toString()

返回标识此池的字符串及其状态,包括运行状态的指示以及估计的工人和任务计数。

Protected methods

void afterExecute(Runnable r, Throwable t)

在完成给定Runnable的执行后调用的方法。

void beforeExecute(Thread t, Runnable r)

在给定线程中执行给定Runnable之前调用的方法。

void finalize()

当这个执行器不再被引用并且它没有线程时调用 shutdown

void terminated()

Executor终止时调用的方法。

Inherited methods

From class java.util.concurrent.AbstractExecutorService
From class java.lang.Object
From interface java.util.concurrent.ExecutorService
From interface java.util.concurrent.Executor

Public constructors

ThreadPoolExecutor

Added in API level 1
ThreadPoolExecutor (int corePoolSize, 
                int maximumPoolSize, 
                long keepAliveTime, 
                TimeUnit unit, 
                BlockingQueue<Runnable> workQueue)

用给定的初始参数和默认线程工厂和拒绝的执行处理程序创建一个新的ThreadPoolExecutor 使用Executors工厂方法之一而不是此通用构造函数可能会更方便。

Parameters
corePoolSize int: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize int: the maximum number of threads to allow in the pool
keepAliveTime long: 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.
unit TimeUnit: the time unit for the keepAliveTime argument
workQueue BlockingQueue: the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
Throws
IllegalArgumentException if one of the following holds:
corePoolSize < 0
keepAliveTime < 0
maximumPoolSize <= 0
maximumPoolSize < corePoolSize
NullPointerException if workQueue is null

ThreadPoolExecutor

Added in API level 1
ThreadPoolExecutor (int corePoolSize, 
                int maximumPoolSize, 
                long keepAliveTime, 
                TimeUnit unit, 
                BlockingQueue<Runnable> workQueue, 
                ThreadFactory threadFactory)

用给定的初始参数和默认拒绝的执行处理程序创建一个新的 ThreadPoolExecutor

Parameters
corePoolSize int: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize int: the maximum number of threads to allow in the pool
keepAliveTime long: 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.
unit TimeUnit: the time unit for the keepAliveTime argument
workQueue BlockingQueue: the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
threadFactory ThreadFactory: the factory to use when the executor creates a new thread
Throws
IllegalArgumentException if one of the following holds:
corePoolSize < 0
keepAliveTime < 0
maximumPoolSize <= 0
maximumPoolSize < corePoolSize
NullPointerException if workQueue or threadFactory is null

ThreadPoolExecutor

Added in API level 1
ThreadPoolExecutor (int corePoolSize, 
                int maximumPoolSize, 
                long keepAliveTime, 
                TimeUnit unit, 
                BlockingQueue<Runnable> workQueue, 
                RejectedExecutionHandler handler)

用给定的初始参数和默认线程工厂创建一个新的 ThreadPoolExecutor

Parameters
corePoolSize int: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize int: the maximum number of threads to allow in the pool
keepAliveTime long: 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.
unit TimeUnit: the time unit for the keepAliveTime argument
workQueue BlockingQueue: the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
handler RejectedExecutionHandler: 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:
corePoolSize < 0
keepAliveTime < 0
maximumPoolSize <= 0
maximumPoolSize < corePoolSize
NullPointerException if workQueue or handler is null

ThreadPoolExecutor

Added in API level 1
ThreadPoolExecutor (int corePoolSize, 
                int maximumPoolSize, 
                long keepAliveTime, 
                TimeUnit unit, 
                BlockingQueue<Runnable> workQueue, 
                ThreadFactory threadFactory, 
                RejectedExecutionHandler handler)

用给定的初始参数创建一个新的 ThreadPoolExecutor

Parameters
corePoolSize int: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize int: the maximum number of threads to allow in the pool
keepAliveTime long: 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.
unit TimeUnit: the time unit for the keepAliveTime argument
workQueue BlockingQueue: the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
threadFactory ThreadFactory: the factory to use when the executor creates a new thread
handler RejectedExecutionHandler: 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:
corePoolSize < 0
keepAliveTime < 0
maximumPoolSize <= 0
maximumPoolSize < corePoolSize
NullPointerException if workQueue or threadFactory or handler is null

Public methods

allowCoreThreadTimeOut

Added in API level 9
void allowCoreThreadTimeOut (boolean value)

设置策略来管理核心线程是否可能超时并在保持活动时间内没有任何任务到达时终止,当新任务到达时如果需要则替换。 如果为false,则由于缺少传入任务,核心线程永远不会终止。 如果为true,则适用于非核心线程的保持活动策略也适用于核心线程。 为避免不断更换螺纹,设置true时,保持时间必须大于零。 通常应在池被积极使用之前调用此方法。

Parameters
value boolean: true if should time out, else false
Throws
IllegalArgumentException if value is true and the current keep-alive time is not greater than zero

allowsCoreThreadTimeOut

Added in API level 9
boolean allowsCoreThreadTimeOut ()

如果此池允许核心线程超时并在keepAlive时间内没有任何任务到达时终止,则返回true;如果新任务到达时需要替换,则返回true。 如果为true,则适用于非核心线程的保持活动策略也适用于核心线程。 如果为false(缺省值),则由于缺少传入任务,核心线程永远不会终止。

Returns
boolean true if core threads are allowed to time out, else false

awaitTermination

Added in API level 1
boolean awaitTermination (long timeout, 
                TimeUnit unit)

Parameters
timeout long
unit TimeUnit
Returns
boolean
Throws
InterruptedException

execute

Added in API level 1
void execute (Runnable command)

将来执行给定的任务。 该任务可以在新线程或现有池化线程中执行。 如果任务无法提交执行,或者因为此执行程序已关闭或因其容量已达到,则该任务由当前RejectedExecutionHandler处理。

Parameters
command Runnable: the task to execute
Throws
RejectedExecutionException at discretion of RejectedExecutionHandler, if the task cannot be accepted for execution
NullPointerException if command is null

getActiveCount

Added in API level 1
int getActiveCount ()

返回正在执行任务的线程的近似数量。

Returns
int the number of threads

getCompletedTaskCount

Added in API level 1
long getCompletedTaskCount ()

返回已完成执行的大约总任务数。 由于任务和线程的状态可能在计算过程中动态地改变,所以返回的值只是一个近似值,但是在连续的调用中不会降低。

Returns
long the number of tasks

getCorePoolSize

Added in API level 1
int getCorePoolSize ()

返回线程的核心数量。

Returns
int the core number of threads

也可以看看:

getKeepAliveTime

Added in API level 1
long getKeepAliveTime (TimeUnit unit)

返回线程保持活动时间,这是线程在终止之前可能保持空闲的时间量。 如果有超过当前在池中的线程的核心数量,或者如果该池为allows core thread timeout ,那么等待此时间量而不处理任务的线程将被终止。

Parameters
unit TimeUnit: the desired time unit of the result
Returns
long the time limit

也可以看看:

getLargestPoolSize

Added in API level 1
int getLargestPoolSize ()

返回池中同时存在的最大线程数。

Returns
int the number of threads

getMaximumPoolSize

Added in API level 1
int getMaximumPoolSize ()

返回允许的最大线程数。

Returns
int the maximum allowed number of threads

也可以看看:

getPoolSize

Added in API level 1
int getPoolSize ()

返回池中的当前线程数。

Returns
int the number of threads

getQueue

Added in API level 1
BlockingQueue<Runnable> getQueue ()

返回此执行程序使用的任务队列。 访问任务队列主要用于调试和监视。 该队列可能处于活动状态。 检索任务队列不会阻止排队的任务执行。

Returns
BlockingQueue<Runnable> the task queue

getRejectedExecutionHandler

Added in API level 1
RejectedExecutionHandler getRejectedExecutionHandler ()

返回不可执行任务的当前处理程序。

Returns
RejectedExecutionHandler the current handler

也可以看看:

getTaskCount

Added in API level 1
long getTaskCount ()

返回曾经计划执行的任务的近似总数。 由于任务和线程的状态可能在计算过程中动态地改变,返回的值只是一个近似值。

Returns
long the number of tasks

getThreadFactory

Added in API level 1
ThreadFactory getThreadFactory ()

返回用于创建新线程的线程工厂。

Returns
ThreadFactory the current thread factory

也可以看看:

isShutdown

Added in API level 1
boolean isShutdown ()

Returns
boolean

isTerminated

Added in API level 1
boolean isTerminated ()

Returns
boolean

isTerminating

Added in API level 1
boolean isTerminating ()

如果此执行程序正在shutdown()shutdownNow()之后终止,但尚未完全终止,则返回true。 该方法可能对调试有用。 报告true报告关闭后的足够时间可能表明提交的任务已忽略或抑制中断,导致此执行程序未正确终止。

Returns
boolean true if terminating but not yet terminated

prestartAllCoreThreads

Added in API level 1
int prestartAllCoreThreads ()

启动所有核心线程,导致它们空闲地等待工作。 这会覆盖仅在执行新任务时启动核心线程的默认策略。

Returns
int the number of threads started

prestartCoreThread

Added in API level 1
boolean prestartCoreThread ()

启动一个核心线程,导致它闲置地等待工作。 这会覆盖仅在执行新任务时启动核心线程的默认策略。 如果所有核心线程都已启动,此方法将返回false

Returns
boolean true if a thread was started

purge

Added in API level 1
void purge ()

尝试从工作队列中删除已取消的所有Future任务。 此方法可用作存储回收操作,对功能没有其他影响。 取消的任务永远不会执行,但可能会积累在工作队列中,直到工作线程可以主动删除它们。 相反,现在调用此方法试图将其删除。 但是,此方法可能无法在存在其他线程干扰的情况下删除任务。

remove

Added in API level 1
boolean remove (Runnable task)

如果该任务存在,则从执行程序的内部队列中删除此任务,从而导致它在尚未启动的情况下不会运行。

该方法可能作为取消方案的一部分有用。 在放入内部队列之前,它可能无法删除已转换为其他形式的任务。 例如,使用submit输入的任务可能会转换为维护Future状态的表单。 但是,在这种情况下,方法purge()可能被用来删除那些已被取消的期货。

Parameters
task Runnable: the task to remove
Returns
boolean true if the task was removed

setCorePoolSize

Added in API level 1
void setCorePoolSize (int corePoolSize)

设置线程的核心数量。 这将覆盖构造函数中设置的任何值。 如果新值小于当前值,那么多余的现有线程在下一次空闲时将被终止。 如果更大,新线程将在需要时开始执行任何排队的任务。

Parameters
corePoolSize int: the new core size
Throws
IllegalArgumentException if corePoolSize < 0

也可以看看:

setKeepAliveTime

Added in API level 1
void setKeepAliveTime (long time, 
                TimeUnit unit)

设置线程保持活动时间,这是线程在终止之前可能保持空闲的时间量。 如果有超过当前在池中的线程的核心数量,或者如果此池为allows core thread timeout ,那么等待此时间量而不处理任务的线程将被终止。 这将覆盖构造函数中设置的任何值。

Parameters
time long: the time to wait. A time value of zero will cause excess threads to terminate immediately after executing tasks.
unit TimeUnit: the time unit of the time argument
Throws
IllegalArgumentException if time less than zero or if time is zero and allowsCoreThreadTimeOut

也可以看看:

setMaximumPoolSize

Added in API level 1
void setMaximumPoolSize (int maximumPoolSize)

设置允许的最大线程数。 这将覆盖构造函数中设置的任何值。 如果新值小于当前值,那么多余的现有线程在下一次空闲时将被终止。

Parameters
maximumPoolSize int: the new maximum
Throws
IllegalArgumentException if the new maximum is less than or equal to zero, or less than the core pool size

也可以看看:

setRejectedExecutionHandler

Added in API level 1
void setRejectedExecutionHandler (RejectedExecutionHandler handler)

为不可执行的任务设置新的处理程序。

Parameters
handler RejectedExecutionHandler: the new handler
Throws
NullPointerException if handler is null

也可以看看:

setThreadFactory

Added in API level 1
void setThreadFactory (ThreadFactory threadFactory)

设置用于创建新线程的线程工厂。

Parameters
threadFactory ThreadFactory: the new thread factory
Throws
NullPointerException if threadFactory is null

也可以看看:

shutdown

Added in API level 1
void shutdown ()

启动先前提交的任务执行的有序关闭,但不会接受新任务。 如果已关闭,调用没有其他影响。

此方法不会等待先前提交的任务完成执行。 使用awaitTermination来做到这一点。

shutdownNow

Added in API level 1
List<Runnable> shutdownNow ()

尝试停止所有正在执行的任务,暂停等待任务的处理,并返回正在等待执行的任务列表。 从此方法返回后,这些任务将从任务队列中排出(除去)。

此方法不会等待主动执行的任务终止。 使用awaitTermination来做到这一点。

除了竭尽全力尝试停止处理主动执行的任务之外,没有任何保证。 该实现通过interrupt()中断任务; 任何不能响应中断的任务可能永远不会终止。

Returns
List<Runnable>

toString

Added in API level 1
String toString ()

返回标识此池的字符串及其状态,包括运行状态的指示以及估计的工人和任务计数。

Returns
String a string identifying this pool, as well as its state

Protected methods

afterExecute

Added in API level 1
void afterExecute (Runnable r, 
                Throwable t)

在完成给定Runnable的执行后调用的方法。 该方法由执行任务的线程调用。 如果非null,则Throwable是导致执行突然终止的未捕获的RuntimeExceptionError

这个实现什么都不做,但可以在子类中定制。 注意:要正确嵌套多个重写,子类通常应该在此方法的开始处调用super.afterExecute

注意:当任务明确地或通过诸如submit等方法将任务包含在任务(如FutureTask )中时,这些任务对象会捕获并维护计算异常,因此它们不会导致突然终止,并且内部异常不会传递给此方法。 如果您希望在此方法中捕获这两种失败,则可以进一步探查此类情况,例如在此示例子类中打印任务已中止的直接原因或基础异常:

 class ExtendedExecutor extends ThreadPoolExecutor {
   // ...
   protected void afterExecute(Runnable r, Throwable t) {
     super.afterExecute(r, t);
     if (t == null
         && r instanceof Future<?>
         && ((Future<?>)r).isDone()) {
       try {
         Object result = ((Future<?>) r).get();
       } catch (CancellationException ce) {
         t = ce;
       } catch (ExecutionException ee) {
         t = ee.getCause();
       } catch (InterruptedException ie) {
         // ignore/reset
         Thread.currentThread().interrupt();
       }
     }
     if (t != null)
       System.out.println(t);
   }
 }

Parameters
r Runnable: the runnable that has completed
t Throwable: the exception that caused termination, or null if execution completed normally

beforeExecute

Added in API level 1
void beforeExecute (Thread t, 
                Runnable r)

在给定线程中执行给定Runnable之前调用的方法。 此方法由线程t调用,该线程将执行任务r ,并可用于重新初始化ThreadLocals或执行日志记录。

这个实现什么都不做,但可以在子类中定制。 注意:要正确地嵌套多个重写,子类通常应该在此方法结束时调用super.beforeExecute

Parameters
t Thread: the thread that will run task r
r Runnable: the task that will be executed

finalize

Added in API level 1
void finalize ()

当这个执行器不再被引用并且它没有线程时调用 shutdown

terminated

Added in API level 1
void terminated ()

Executor终止时调用的方法。 默认实现什么都不做。 注意:要正确嵌套多个重写,子类通常应该在此方法中调用super.terminated

Hooray!