欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

ThreadPoolExecutor的使用方法

时间:2023-07-31
ThreadPoolExecutor的使用方法 ThreadPoolExecutor介绍

ThreadPoolExecutor是Java提供的线程池,对ThreadPoolExecutor线程池而言,总共有一下几个概念:

1、核心线程数2、线程池容量3、线程空闲时间4、线程工作队列5、线程工厂6、线程拒绝策略

下面将分别讲解这几个概念

核心线程数
线程池一直维持的最低线程数,决定了在超过线程空闲时间后线程池维持的线程数。线程池容量
线程池的最大线程数,决定了线程池能够开辟的最大线程数量线程空闲时间
当线程池中空闲线程数量超过了核心线程数时,多余的线程会在多长时间内被销毁线程工作队列
任务队列,被添加到线程池中,但尚未被执行的任务;线程工厂
用于创建线程任务拒绝策略
当任务超过了线程工作队列时,对任务的拒绝策略 ThreadPoolExecutor创建

下图是ThreadPoolExecutor的构造函数

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue 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; }

构造函数中共有下列参数

corePoolSize(核心线程数)maximumPoolSize(线程池容量)keepAliveTime(线程空闲时间)unit(线程空闲时间单位)workQueue(线程工作队列)threadFactory(线程工厂)handler(线程拒绝策略)
与前文中线程池的基本概念相似,就不在赘述了。

当然,我们也可以采用Java提供的Executors来创建ThreadPoolExecutor。

ThreadPoolExecutor使用

对于线程池ThreadPoolExecutor而言,它实现了ExecutorService接口,因此它的基本使用可以看ExecutorService的使用方法

// 创建线程池 ThreadPoolExecutor executor = new ThreadPoolExecutor( // 核心线程数量 1, // 线程池容量 1, // 线程保持活动时间 1000, // 线程保持活动单位 TimeUnit.SECONDS, // 线程任务队列 new linkedBlockingQueue<>(1024), // 线程创建工厂 Executors.defaultThreadFactory(), // 线程拒绝策略 new ThreadPoolExecutor.AbortPolicy()); // 通过循环向线程池中添加10个任务 for (int i = 0; i < 10; i++) { executor.execute(() -> { LogUtils.info("info execute"); }); } // 关闭线程池 executor.shutdown();

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。