import .*;
public class ExecutorTest {
public static void main(String[] args) {
// 创建线程池 , 参数含义 :(核心线程数,最大线程数,加开线程的存活时间,时间单位,任务队列长度)
ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 8,
0L, ,
new LinkedBlockingQueue<Runnable>(2));
//设置:任务数 = 3 ~ 11 ,分析:任务数 与 活跃线程数,核心线程数,队列长度,最大线程数的关系。
int a = 3;
for (int i = 1; i <= a; i++) {
int j = i;
(new Runnable() {
@Override
public void run() {
//获取线程名称
Thread thread = ();
String name = ();
//输出
int activeCount = ();
("任务:"+j+"-----,线程名称:"+name+"-----活跃线程数:"+activeCount);
}
});
}
//关闭线程池
();
}
}
输出结果,观察关系:
# 任务数 a = 3 , 活跃线程数3 , 任务数 < 核心线程数。
# 任务数 a = 4 , 活跃线程数4 , 任务数 < 核心线程数。
# 任务数 a = 5 , 活跃线程数5 , 任务数 = 核心线程数。
# 任务数 a = 6 , 活跃线程数5 , 任务数 < 核心线程数5 + 队列长度2 。
# 任务数 a = 7 , 活跃线程数5 , 任务数 = 核心线程数5 + 队列长度2 。
# 任务数 a = 8 , 活跃线程数6 , 任务数 < 最大线程数8 + 队列长度2 。活跃线程数是在核心线程数5的基础上,加1个活跃线程。
# 任务数 a = 9 , 活跃线程数7 , 任务数 < 最大线程数8 + 队列长度2 。活跃线程数是在核心线程数5的基础上,加2个活跃线程。
# 任务数 a = 10 , 活跃线程数8 , 任务数 = 最大线程数8 + 队列长度2 。活跃线程数是在核心线程数5的基础上,加3个活跃线程。
# 任务数 a = 11 , 活跃线程数8 , 任务数 > 最大线程数8 + 队列长度2 。抛出异常RejectedExecutionException
# 总结
随着任务数量的增加,会增加活跃的线程数。
当活跃的线程数 = 核心线程数,此时不再增加活跃线程数,而是往任务队列里堆积。
当任务队列堆满了,随着任务数量的增加,会在核心线程数的基础上加开线程。
直到活跃线程数 = 最大线程数,就不能增加线程了。
如果此时任务还在增加,则: 任务数11 > 最大线程数8 + 队列长度2 ,抛出异常RejectedExecutionException,拒绝任务
public final class TaskPoolManager {
/** 默认线程池核心线程数.
*
*/
static final int DEFAULT_CORE_POOL_SIZE = 16;
/** 默认线程池最大允许线程数.
*
*/
static final int DEFAULT_MAX_POOL_SIZE = 30;
/** 默认线程池中空闲线程的存活时间.
* 30 s
*/
static final long DEFAULT_KEEP_ALIVE_TIME = 30000L;
/** 默认线程池中等待队列中允许等待的最大线程数.
* 按照3小时切分,一天8个任务,一个月240个任务,当前队列设置3个月线程数
*/
static final int DEFAULT_WAIT_QUEUE_SIZE = 720;
/** 线程池.
* 采用固定长度的阻塞队列,同时使用 CallerRunsPolicy 拒绝策略
* 当阻塞队列无法再加入新任务时,将任务交给提交任务的线程执行,也就是谁提交任务,谁就负责执行任务
*/
private static ThreadPoolExecutor pool = new ThreadPoolExecutor(
DEFAULT_CORE_POOL_SIZE, DEFAULT_MAX_POOL_SIZE,
DEFAULT_KEEP_ALIVE_TIME, ,
new ArrayBlockingQueue<Runnable>(DEFAULT_WAIT_QUEUE_SIZE),
new ());
/** 私有化构造方法,禁止实例化.
*
*/
private TaskPoolManager() { }
/** 提交工作线程.
*
* @param runnable 任务实例
* @return 提交任务结果
*/
public static Boolean submit(final Runnable runnable) {
(runnable);
return true;
}
}