一、线程池七大参数
1,corePoolSize:核心线程数
1.1 CPU密集型
核心线程基本是并行的,单核单线程就设置1倍,单核双线程设置为2倍
1.2 I/O密集型
I/O请求较多,网络处理比CPU处理的慢很多,所以可以多设置CPU几倍
经过压测计算出几倍合适,再设置
2,workQueue:工作队列
2.1 ArrayBlockingQueue
有固定大小的队列
见名之意,Array 数组的意思,数组创建的时候就规定大小,如果想扩容,则需要重新创建
final Object[] items;
private final Condition notEmpty;
private final Condition notFull;
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
//从这可以看出和ArrayList思想相似
this.items = new Object[capacity];
//创建定义个非公平锁
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
2.2 LinkedBlockingQueue
无限制添加工作任务的队列
linked 链表思索
既然无限制的往工作队列添加,就必须要考虑内存问题了,可能发生OOM
2.3 SynchronousQueue
没有存储能力的队列
既然工作队列没有存储能力,那就意味着来一个任务执行一个任务,可以和maximumPoolSize一起使用
2.4 PriorityBlockingQueue
有优先级的工作队列
3,maximumPoolSize:最大线程数
设置为设置为Integer最大值的话,那线程就用不完的用了,可能引发OOM异常
4,keepAliveTime:线程存活时间
非核心线程的存活时间(maximumPoolSize-corePoolSize)
5,unit:存活时间单位
TimeUnit枚举类
6,ThreadFactory
一般情况用默认的
7,RejectedExecutionHandler:拒绝策略
public interface RejectedExecutionHandler {
//不同的实现方法对应不同的拒绝策略,方法体--对新任务的处理逻辑
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}
public boolean isShutdown() {
return ! isRunning(ctl.get());
}
7.1 触发时机
线程池关闭的时候
最大线程数达到上限
7.2 AbortPolicy(默认的)
不执行新任务并抛出RejectedExecutionException异常
private static final RejectedExecutionHandler defaultHandler =new AbortPolicy();
public static class AbortPolicy implements RejectedExecutionHandler {
public AbortPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
7.3 DiscardPolicy
不执行新任务
public static class DiscardPolicy implements RejectedExecutionHandler {
public DiscardPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}
7.4 DiscardOldestPolicy
抛弃任务队列中最老的任务
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
public DiscardOldestPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
//删除此队列的头
e.getQueue().poll();
e.execute(r);
}
}
}
7.5 CallerRunsPolicy
线程池关闭的情况,拒绝新任务
public static class CallerRunsPolicy implements RejectedExecutionHandler {
public CallerRunsPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}
二、线程池
1,优劣势
提高响应速度
CPU和内存资源合理使用
方便统一管理
2,种类
区别在于工作队列,核心和最大线程池;同一种线程池ThreadFactory
2.1 newFixedThreadPool
核心线程==最大线程;队列=LinkedBlockingQueue
2.2 newSingleThreadExecutor
核心线程==最大线程=1;队列=LinkedBlockingQueue
2.3 newCachedThreadPool
核心=0;最大=Integer.MAX_VALUE;队列=SynchronousQueue
2.4 newScheduledThreadPool
延迟和定时执行任务
2.5 newWorkStealingPool
1.8加入,在自己空闲的时候可以窃取别的线程的任务
3,创建和关闭API
package threadpool;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ShutDown {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 200; i++) {
Runnable runnable=() -> {
System.out.println(Thread.currentThread().getName());
};
executorService.submit(runnable);
}
System.out.println("================isShutdown="+executorService.isShutdown());
executorService.shutdown();
//isShutdown()只要关闭就返回true
System.out.println("================isShutdown="+executorService.isShutdown());
System.out.println("================isTerminated="+executorService.isTerminated());
//关闭线程池,未执行的任务都存list
List<Runnable> list = executorService.shutdownNow();
//isTerminated()任务全部执行完才返回true
System.out.println("================isShutdown="+executorService.isShutdown());
System.out.println("================isTerminated="+executorService.isTerminated());
System.out.println(list);
}
}
4,线程池的状态
4.1 running
正在运行,也接收新任务
4.2 shutdown
线程池关闭,也正在执行新任务
4.3 stop
调用shutDownNow可以进入此状态
4.4 tidying
所有线程停止,workCount为0;运行terminate()钩子方法
4.5 terminated
terminate()运行完成