ThreadPoolExecutor关键字 包括五个参数 corePoolSize、maximumPool、keepAliveTime、unit、workQueue
corePoolSize表示核心进程数, maximumPool表示最大线程数、workQueue表示阻塞队列中进程数
用一个通俗易懂的例子来理解,core这个核心进程数相当于银行工作窗口,workqueue在排队办理业务的人、max表示能开启总共的总窗口。
core设为5,max设为10(其中包括core的5个 剩余的是临时的),workqueue设为20则
情况1 来了20个人 会直接去排队 其中的5个人等着核心core处理
情况2 来了25个人 5个人去core办理 剩余20个人把排队的位子坐满
情况3 来了26个人 前25个人和情况2类似 最后到的1个人 直接到临时窗口办理业务
情况4 来了30个人 其中25个人情况处理和情况2类似 剩余的5个人会直接把剩余的5个临时窗口站全了
情况5 来了31个人 那么前三十个人和情况三类似 舍弃最后一个人(线程池的执行策略:拒绝执行)
补充:临时窗口啥时候关闭呢?当所有的窗口都空闲时,并且空闲的时间超过keepAliveTime,那么5个临时窗口会全部关闭,5个core核心窗口保持打开。
代码示例:
public class ThreadPool {
//工作进程列表
private List<WorkThread> workList = new ArrayList<>();
//任务线程
private List<Runnable> runnableList = new ArrayList<>();
private int coreSize;
private int maxSize;
private int queueSize;
public ThreadPool(int coreSize,int maxSize,int queueSize){
this.coreSize = coreSize;
this.maxSize = maxSize;
this.queueSize = queueSize;
//启动任务
for(int i = 0; i < coreSize; i++){
WorkThread work = new WorkThread(runnableList);
new Thread(work).start();
workList.add(work);
}
}
public void add(Runnable runnable){
synchronized (runnableList){
if(runnableList.size() < queueSize){ //核心进程工作
//添加并唤醒
runnableList.add(runnable);
runnableList.notify();
}else if(workList.size() < maxSize){ //临时进程工作
System.out.println("临时进程启用");
WorkThread work = new WorkThread(runnableList);
new Thread(work).start();
workList.add(work);
//让创建的临时进程处理任务
runnableList.add(runnable);
runnableList.notify();
}else{
System.out.println("拒绝执行");
}
}
}
}
public class WorkThread implements Runnable{
private List<Runnable> runnableList;
public WorkThread(List<Runnable> runnableList){
this.runnableList = runnableList;
}
public void run(){
Runnable runnable = null;
while(true){
synchronized (runnableList) {
//判断是否为空
while (runnableList.isEmpty()) {
//执行等待
try {
runnableList.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//不空继续执行 取出进程
runnable = runnableList.remove(0);
}
//执行进程代码
runnable.run();
}
}
}
public class Test {
public static void main(String[] args){
//传值
ThreadPool pool = new ThreadPool(5,10,20);
for(int i = 0; i < 20; i++){
pool.add(new TestWork(i));
}
}
//自定义任务类
static class TestWork implements Runnable{
private int count;
public TestWork(int count){
this.count = count;
}
public void run(){
//延时
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + "执行进程: " + count);
}
}
}
可以调整任务数来观察结果,会完全符合上述的运行逻辑