一句话概括:三大方法、7大参数、4种拒绝策略
程序的运行,本质:占用系统的资源 优化资源的使用 =》 池化技术
线程池、连接池、内存池、对象池。。。
池化技术:事先准备好一些资源,有人要用,就来我这里拿,用完之后还我。
线程池好处:
- 降低资源的消耗
- 提高响应的速度
- 方便管理
线程复用、可以控制最大并发数、管理线程
三大方法
//固定线程数池
ExecutorService executorService = Executors.newFixedThreadPool(5);
//单例线程池
ExecutorService executorService1 = Executors.newSingleThreadExecutor();
//缓存线程数池
ExecutorService executorService2 = Executors.newCachedThreadPool();
try {
for (int i = 0; i < 10; i++) {
executorService.execute(()->{
System.out.println(Thread.currentThread().getName()+" ok");
});
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//线程池用完,程序结束,关闭线程池
executorService1.shutdown();
}
7大参数
//获取cpu核心
System.out.println(Runtime.getRuntime().availableProcessors());
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
2,// 核心线程数
Runtime.getRuntime().availableProcessors(),// 最大核心线程数
3,// 超时时间
TimeUnit.SECONDS,// 超时单位
new LinkedBlockingDeque<>(3),// 阻塞队列
Executors.defaultThreadFactory(),// 默认线程工厂,不用动它
new ThreadPoolExecutor.AbortPolicy() //线程池处理不过来就抛出异常(拒绝策略)
);
try {
for (int i = 0; i < 20; i++) {
threadPoolExecutor.execute(()->{
System.out.println(Thread.currentThread().getName()+" ok");
});
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//线程池用完,程序结束,关闭线程池
threadPoolExecutor.shutdown();
}
最大线程数怎么定义:
- cpu 密集型 :几核,就是几,可以保持cpu的效率最高
- io 密集型 :判断你程序中十分耗费io的线程
4种拒绝策略
/**
*
* new ThreadPoolExecutor.AbortPolicy() 线程池处理不过来就抛出异常
* new ThreadPoolExecutor.CallerRunsPolicy() 哪来的去哪里
* new ThreadPoolExecutor.DiscardPolicy() 队列满了,丢掉任务,不会抛异常
* new ThreadPoolExecutor.DiscardOldestPolicy() 队列满了,尝试去和最早的竞争,也不会抛出异常
*
*/