
由类图结构可知:
void execute(Runnable command) 在将来的某个时间执行给定的命令。 该命令可以在一个新线程,一个合并的线程中或在调用线程中执行,由Executor实现。
注:通过Executors类的方式创建线程池,参考lz此博文链接https://www./article/215163.htm
1.ThreadPoolExecutor类中的构造方法
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue workQueue,defaultHandler)
2、 ThreadPoolExecutor类中构造函数的参数解析
3、ThreadPoolExecutor类创建线程池示例
代码
package com.xz.thread.executor;
import java.util.concurrent.*;
/**
* @description:
* @author: xz
* @create: 2025-06-16 22:16
*/
public class Demo {
public static void main(String[] args) {
ThreadPoolExecutor pool = new ThreadPoolExecutor(3,3,
1L, TimeUnit.MINUTES,new LinkedBlockingDeque<>());
for(int i=1;i<=5;i++){
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
System.out.println("睡眠一秒钟");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}
输出结果如下图
结论:无论是创建何种类型线程池(newFixedThreadPool、newSingleThreadExecutor、newCachedThreadPool等等),均会调用ThreadPoolExecutor构造函数。