2025.02.20笔记 ~ langhai

2025.02.20笔记
线程的核心参数:
核心线程数量
数量确定方法
IO密集型任务 文件读写 DB读写 网络请求 2N + 1
CPU密集型任务 计算型代码 N + 1
最大线程数量
生存时间
时间单位(这两个时间参数 指的是救济线程的存活时间 生存的时间内 没有新的任务 就会释放线程资源)
任务队列 (当没有核心线程的时候 新进来的任务就会在此队列中进行排队 当队列满了 就会创建救济线程来执行任务)
ArrayBlockQueue:数组结构 FIFO 有界阻塞队列 强制有界 初始化必须给定容量 一把锁
LinkedBlockQueue:链表结构 单向链表 FIFO 有界阻塞队列 默认无界 支持有界 两把锁(头尾)
DelayedWorkQueue:优先级队列
SynchronousQueue:不存储元素的阻塞队列
线程工厂(用来定制线程的创建 例如 设置线程名字 是否是守护线程等)
拒绝策略(所有线程都在工作 任务队列也已经满了 就会执行此策略)
拒绝策略:直接抛出异常 默认策略,调用者所在线程来处理任务,丢弃阻塞队列中最前的任务,直接丢弃。
线程池的种类?
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
源代码可以看出 核心线程数量和最大线程数量一样 阻塞队列 LinkedBlockQueue 最大容量是Integer.MAX_VALUE 适用任务量已知 相对耗时的任务
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
核心线程和最大线程数量都是1 阻塞队列 LinkedBlockQueue 最大容量是Integer.MAX_VALUE 适用于按照顺序执行的任务
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
核心线程数量为0 最大线程数量 Integer.MAX_VALUE 阻塞队列不存储元素 任务数量 比较密集 每个任务执行时间比较短的情况
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
可以执行延迟任务的队列,支持定时及周期性执行任务