java并发包Executors中的4种线程池

本文详细介绍了Java中Executors类提供的四种线程池创建方式,包括动态调整线程数的newCachedThreadPool、固定线程数的newFixedThreadPool、可定时执行任务的newScheduledThreadPool以及单线程的newSingleThreadExecutor。

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

Executors类中,提供可创建的四种大类的线程池

1. newCachedThreadPool

一句话说清:动态创建线程和移除60s不用的老线程。
适合的场景:拥有大量执行时间短的异步任务。

/**
     * 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
     */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
2. newFixedThreadPool

一句话说清:创建固定数量的线程,如果全部线程被占用,新进的任务需进入阻塞队列等待。

  /**
     * 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>());
    }
3. newScheduledThreadPool

一句话说清:可以安排任务延迟多少时间后执行或周期执行

4. newSingleThreadExecutor

一句话说清:创建有且只有一个线程的线程池,除非遇到意外终止,否则一直都是这个线程在工作,并保证等待线程顺序执行。

/**
     * 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>()));
    }
其他说明:

fixed和cache都会设置线程池大小,区别是cache会动态平衡,并且线程数可以为0,fix要维持这个数的线程在池子里。
newFixedThreadPool(1)和newSingleThreadExecutor的区别是:
fix可能会被reconfig,像下面这样,但是single可以保证不会

((ThreadPoolExecutor)newFixedThreadPool(1)).setCorePoolSize(3);

参考:
[https://segmentfault.com/a/1190000014944049?utm_source=tag-newest]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值