Java线程池,Executor.java文件的详细解读

本文深入探讨了Java中Executor框架的使用,包括newFixedThreadPool、newSingleThreadExecutor、newCachedThreadPool、newScheduledThreadPool和newWorkStealingPool等方法的详细解析。介绍了线程池的参数设置、工作原理及适用场景,特别强调了ForkJoinPool在计算密集型任务中的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Executor的使用:

在java.util.concurrent包中,有一个Executors.java文件,类中方法都是static的。

现在介绍其中的方法

1.newFixedThreadPool(int nThreads)
 

/**

* Creates a thread pool that reuses a fixed number of threads

* operating off a shared unbounded queue.  At any point, at most

* {@code nThreads} threads will be active processing tasks.

* If additional tasks are submitted when all threads are active,

* they will wait in the queue until a thread is available.

* If any thread terminates due to a failure during execution

* prior to shutdown, a new one will take its place if needed to

* execute subsequent tasks.  The threads in the pool will exist

* until it is explicitly {@link ExecutorService#shutdown shutdown}.

*

* @param nThreads the number of threads in the pool

* @return the newly created thread pool

* @throws IllegalArgumentException if {@code nThreads <= 0}

*/

public static ExecutorService newFixedThreadPool(int nThreads) {

    return new ThreadPoolExecutor(nThreads, nThreads,

                                  0L, TimeUnit.MILLISECONDS,

                                  new LinkedBlockingQueue<Runnable>());

}

//创建一个固定数量的线程池

//*在一个共享的无界队列queue里面运行,在任何时刻只有nThreads个线程是实际活跃的状态。

//*如果当有额外的任务提交过来,它们将会在这个queue中等待直到有个线程是可用的。

//*如果任何线程在执行期间因故障而终止在shutdown之前,如果需要,新的线程将取代它执行后续任务。

//*池中的线程存在直到线程池明确被shutdown

 

2.newFixedThreadPool(int nThreads, ThreadFactory threadFactory)

/**

相较于上述方法,使用了一个ThreadFactory当创建新线程的时候使用。

*

* @param nThreads the number of threads in the pool

* @param threadFactory the factory to use when creating new threads

* @return the newly created thread pool

* @throws NullPointerException if threadFactory is null

* @throws IllegalArgumentException if {@code nThreads <= 0}

*/

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {

    return new ThreadPoolExecutor(nThreads, nThreads,

                                  0L, TimeUnit.MILLISECONDS,

                                  new LinkedBlockingQueue<Runnable>(),

                                  threadFactory);

}

 

**ThreadPoolExecutor

/*参数介绍 

@param corePoolSize the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set

*@param corePoolSize保存在线程池中的线程数量,就算它们是没有用的空闲的,除非设置了allowCoreThreadTimeOut。

注:当设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭



*@param maximumPoolSize the maximum number of threads to allow in the pool

*@param maximumPoolSize:线程池中允许的最大的线程数量,当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理



*@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 keepAliveTime:当线程数量大于corePoolSize,keepAliveTime时间是线程允许空闲的最大时间,超过这个时间后线程就会被关闭。



*@param unit the time unit for the {@code keepAliveTime} argument

*@param unit:keepAliveTime的时间单位



*@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 workQueue:在线程被调度之前就放在workQueue里面,等待被调度。并且这个队列只会存放通过execute.submitted方法提交的Runnable任务

* @throws IllegalArgumentException if one of the following holds:



*         {@code corePoolSize < 0}



*         {@code keepAliveTime < 0}



*         {@code maximumPoolSize <= 0}



*         {@code maximumPoolSize < corePoolSize}

* @throws NullPointerException if {@code workQueue} is null

*/

public ThreadPoolExecutor(int corePoolSize,

                          int maximumPoolSize,

                          long keepAliveTime,

                          TimeUnit unit,

                          BlockingQueue<Runnable> workQueue) {

    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,

         Executors.defaultThreadFactory(), defaultHandler);

}

3.newWorkStealingPool                                                                                                          

/**

* Creates a thread pool that maintains enough threads to support

* the given parallelism level, and may use multiple queues to

* reduce contention. The parallelism level corresponds to the

* maximum number of threads actively engaged in, or available to

* engage in, task processing. The actual number of threads may

* grow and shrink dynamically. A work-stealing pool makes no

* guarantees about the order in which submitted tasks are

* executed.

*创建一个线程池,该线程池维护足够的线程以支持给定的并行度级别,并且可以使用多个队列来减少争用。

*并行度级别对应于主动参与或可用于任务处理的线程的最大数量。

*实际线程数可能会动态增长和缩小。

*work-stealing不保证提交任务的执行顺序

* @param parallelism the targeted parallelism level

* @return the newly created thread pool

* @throws IllegalArgumentException if {@code parallelism <= 0}

* @since 1.8

*/

public static ExecutorService newWorkStealingPool(int parallelism) {

    return new ForkJoinPool

        (parallelism,

         ForkJoinPool.defaultForkJoinWorkerThreadFactory,

         null, true);

}

newWorkStealingPool适合使用在很耗时的操作,但是newWorkStealingPool不是ThreadPoolExecutor的扩展,

它是新的线程池类ForkJoinPool的扩展,但是都是在统一的一个Executors类中实现,

由于能够合理的使用CPU进行对任务操作(并行操作),所以适合使用在很耗时的任务中。

当不传入参数时候,直接创建一个work-stealing线程池使用当前所有可用的线程作为当前的并行等级。



注意:ForkJoinPool 可以根据CPU的核数并行的执行,适合使用在很耗时的操作,可以充分的利用CPU执行任务。

ForkJoinPool 不是为了替代 ExecutorService,而是它的补充,在某些应用场景下性能比 ExecutorService 更好。

ForkJoinPool 主要用于实现“分而治之”的算法,特别是分治之后递归调用的函数,例如 quick sort 等。

ForkJoinPool 最适合的是计算密集型的任务,如果存在 I/O,线程间同步,sleep() 等会造成线程长时间阻塞的情况时,

最好配合使用 ManagedBlocker。

4.newSingleThreadExecutor

 

/**

   *创建一个Executor,它使用一个在无界队列中运行的工作线程。(但请注意,如果此单个线程由于在关闭之前执行期间的故障而终止,则在需要执行后续任务时将使用新的线程.)保证任务按顺序执行,并且不会有多个任务处于活动状态 在任何给定的时间。 与其他等效的{@code newFixedThreadPool(1)}不同,保证返回的执行程序不可重新配置以使用其他线程。

      * @return新创建的单线程Executor

* Creates an Executor that uses a single worker thread operating

* off an unbounded queue. (Note however that if this single

* thread terminates due to a failure during execution prior to

* shutdown, a new one will take its place if needed to execute

* subsequent tasks.)  Tasks are guaranteed to execute

* sequentially, and no more than one task will be active at any

* given time. Unlike the otherwise equivalent

* {@code newFixedThreadPool(1)} the returned executor is

* guaranteed not to be reconfigurable to use additional threads.

*

* @return the newly created single-threaded Executor

*/

public static ExecutorService newSingleThreadExecutor() {

    return new FinalizableDelegatedExecutorService

        (new ThreadPoolExecutor(1, 1,

                                0L, TimeUnit.MILLISECONDS,

                                new LinkedBlockingQueue<Runnable>()));

}



5.newCachedThreadPool()

/**

* Creates a thread pool that creates new threads as needed, but

* will reuse previously constructed threads when they are

* available.  These pools will typically improve the performance

* of programs that execute many short-lived asynchronous tasks.

* Calls to {@code execute} will reuse previously constructed

* threads if available. If no existing thread is available, a new

* thread will be created and added to the pool. Threads that have

* not been used for sixty seconds are terminated and removed from

* the cache. Thus, a pool that remains idle for long enough will

* not consume any resources. Note that pools with similar

* properties but different details (for example, timeout parameters)

* may be created using {@link ThreadPoolExecutor} constructors.

* @return the newly created thread pool

创建一个线程池,会重用之前创建的线程(在它们可用的情况下),通常情况下可以提升效率当处理很多

短暂的异步任务时候。如果没有存在的线程可用,将会创建一个新的线程,如果线程在60s之内没有被使用的话,就会被终止并且移出线程池。

注意:同上,此函数也可以传入一个ThreadFactory,创建自己需要线程。

*/

public static ExecutorService newCachedThreadPool() {

    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,

                                  60L, TimeUnit.SECONDS,

                                  new SynchronousQueue<Runnable>());

}

6.newScheduledThreadPool

可以使用该线程池来实现任务延迟,创建一个线程池,可以调度命令在给定的延迟之后运行,或者定期执行

/**

* Creates a thread pool that can schedule commands to run after a

* given delay, or to execute periodically.

* @param corePoolSize the number of threads to keep in the pool,

* even if they are idle

* @return a newly created scheduled thread pool

* @throws IllegalArgumentException if {@code corePoolSize < 0}

*/

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {

    return new ScheduledThreadPoolExecutor(corePoolSize);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值