Java多线程之线程池

线程池

使用线程池可以不用频繁的创建线程,而是复用已经创建的线程,这样可以降低开销、控制最大并发数

四种线程池

  1. Executors.newSingleThreadExecutor();只包含单线程的线程池,确保任务按顺序执行
  2. Executors.newFixedThreadPool(5);创建一个固定大小的线程池,corePoolSize和maximumPoolSize相等,线程池中的线程不会被回收
  3. newScheduledThreadPool(int corePoolSize);支持定时任务和周期性任务调度
  4. Executors.newCachedThreadPool();缓存线程池(无界线程池),corePoolSize为0,maximumPoolSize为Integer.MAX_VALUE,空闲线程存活时间默认为60秒
    源码
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    } 
public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
 public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

三个源码的均是通过ThreadPoolExecutor 创建线程池,看下ThreadPoolExecutor源码

public ThreadPoolExecutor(int corePoolSize,
                             int maximumPoolSize,
                             long keepAliveTime,
                             TimeUnit unit,
                             BlockingQueue<Runnable> workQueue,
                             ThreadFactory threadFactory,
                             RejectedExecutionHandler handler) {
       if (corePoolSize < 0 ||
           maximumPoolSize <= 0 ||
           maximumPoolSize < corePoolSize ||
           keepAliveTime < 0)
           throw new IllegalArgumentException();
       if (workQueue == null || threadFactory == null || handler == null)
           throw new NullPointerException();
       this.acc = System.getSecurityManager() == null ?
               null :
               AccessController.getContext();
       this.corePoolSize = corePoolSize;
       this.maximumPoolSize = maximumPoolSize;
       this.workQueue = workQueue;
       this.keepAliveTime = unit.toNanos(keepAliveTime);
       this.threadFactory = threadFactory;
       this.handler = handler;
   }

线程池七大参数

由上述源码得知有7个参数

1、corePoolSize:核心线程数,线程池中始终存活的最小线程数,即使这些线程处于空闲状态,也不会被销毁
2、maximumPoolSize:最大线程数,超过此值后新的任务将触发拒绝策略
3、keepAliveTime:空闲线程存活时间,线程池中的线程数大于核心线程数后,超过此时间会回收多余的线程
4、timeUnit:时间单位
5、workQueue:工作队列,存放执行任务的队列
6、threadFactory:线程工厂,用于定制线程的创建
7Handler:拒绝策略

四种拒绝策略

提供了四个预定义的处理程序策略: 
在默认ThreadPoolExecutor.AbortPolicy ,处理程序会引发运行RejectedExecutionException后排斥反应,抛出异常。 
 public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        try {
            for (int i = 1; i <= 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"----ok");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }

执行结果
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-2----ok
pool-1-thread-1----ok
pool-1-thread-3----ok
pool-1-thread-5----ok
pool-1-thread-4----ok
java.util.concurrent.RejectedExecutionException: Task com.song.pool.Demo02$$Lambda$1/1831932724@7699a589 rejected from java.util.concurrent.ThreadPoolExecutor@58372a00[Running, pool size = 5, active threads = 4, queued tasks = 0, completed tasks = 4]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at com.song.pool.Demo02.main(Demo02.java:23)
在ThreadPoolExecutor.CallerRunsPolicy中,调用execute本身的线程运行任务。 这提供了一个简单的反馈控制机制,将降低新任务提交的速度,哪来的回哪由调用者处理。 
public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        try {
            for (int i = 1; i <= 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"----ok");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }


执行结果
pool-1-thread-1----ok
main----ok
pool-1-thread-1----ok
pool-1-thread-5----ok
pool-1-thread-3----ok
pool-1-thread-2----ok
pool-1-thread-5----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
在ThreadPoolExecutor.DiscardPolicy中 ,简单地删除无法执行的任务。 
public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy()
        );
        try {
            for (int i = 1; i <= 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"----ok");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }

执行结果

pool-1-thread-1----ok
pool-1-thread-4----ok
pool-1-thread-1----ok
pool-1-thread-3----ok
pool-1-thread-2----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
pool-1-thread-5----ok
在ThreadPoolExecutor.DiscardOldestPolicy中 ,如果执行程序没有关闭,则工作队列头部的任务被删除,然后重试执行(可能会再次失败,导致重复)
public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        try {
            for (int i = 1; i <= 9; i++) {
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"----ok");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }
执行结果
pool-1-thread-1----ok
pool-1-thread-2----ok
pool-1-thread-3----ok
pool-1-thread-3----ok
pool-1-thread-4----ok
pool-1-thread-5----ok
pool-1-thread-3----ok
pool-1-thread-1----ok
pool-1-thread-4----ok
Java多线程编程中,配置线程池的参数是非常重要的。根据不同的业务需求,可以设置线程池的参数来控制线程的数量和行为。根据引用中的例子,可以使用`Executors.newFixedThreadPool(int nThreads)`来创建一个固定线程数量的线程池。在这个方法中,`nThreads`参数表示线程池中的线程数量,只有这个数量的线程会被创建。然后,可以使用`pool.execute(Runnable command)`方法来提交任务给线程池执行。 在配置线程池时,需要考虑业务的性质。如果是CPU密集型的任务,比如加密、计算hash等,最佳线程数一般为CPU核心数的1-2倍。而如果是IO密集型的任务,比如读写数据库、文件、网络读写等,最佳线程数一般会大于CPU核心数很多倍。这样可以充分利用IO等待时间来执行其他任务,提高程序的性能。引用中给出了一些常见的线程池特点和构造方法参数。 总之,根据业务需求和特点,合理配置线程池的参数可以提高程序的性能和效率。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Java多线程线程池的参数和配置](https://blog.csdn.net/MRZHQ/article/details/129107342)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Java多线程线程池(合理分配资源)](https://blog.csdn.net/m0_52861000/article/details/126869155)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Java多线程线程池](https://blog.csdn.net/weixin_53611788/article/details/129602719)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值