常用线程池
线程池核心类:ThreadPoolExecutor,有7个参数
-
ThreadPoolExecutor
- coreThread,核心线程数
- maxThread 最大线程数
- keepAliveTime线程等待时间
- unit 时间单位
- workQueue 队列
- ThreadFactory 线程工厂,实现ThreadFactory
- handler 阻塞队列的方式
关于handler
- AbortPolicy 超出线程池定义的最大线程和等待队列中的线程数量就会抛出异常
- CallerRunsPolicy 如果线程超过线程最大线程数量和等待队列中的线程数量,不会抛弃线程,也不会抛出异常,而是将线程回退给调用的对象
- DiscardOldestPolicy 【抛弃队列中等待最久的任务,然后将当先任务加入到当前队列中再次提交当前任务
- DiscardPolicy 抛弃超多队列中的任务
-
newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- 核心线程数和最大线程数相等
- newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
- newCachedThreadPool()
coreThread =0,最大线程21亿,相当于无限大
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- newScheduledThreadPool ,核心线程数初始化定义; 阻塞队列优先级队列 DelayedWorkQueue
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
一般情况下线程的实现最好自己写
ExecutorService executorService=new ThreadPoolExecutor(2,
5,
2L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(4),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());
for(int i=0;i<16;i++){
executorService.execute(()-> System.out.println(Thread.currentThread().getName()+"处理任务"));
}
核心线程数量的确定方式:
- 如果是cpu密集型的数据,线程的数量一般是是线程系统核实加1( Runtime.getRuntime().availableProcessors()+1)
- 如果是io密集型的数据,一般有两种情况:
- 1.cpu数量乘以2
- 2 cpu核数/阻塞系数。 一般情况下阻塞系数在0.8~0.9之间