47 lines
1.6 KiB
Java
47 lines
1.6 KiB
Java
|
package thead.pool;
|
|||
|
|
|||
|
import java.util.concurrent.Executors;
|
|||
|
import java.util.concurrent.SynchronousQueue;
|
|||
|
import java.util.concurrent.ThreadPoolExecutor;
|
|||
|
import java.util.concurrent.TimeUnit;
|
|||
|
|
|||
|
public class ThreadPoolNewCached03CustomCachedThreadPool {
|
|||
|
|
|||
|
public static void main(String[] args) {
|
|||
|
// 定制化线程池
|
|||
|
ThreadPoolExecutor executor = new ThreadPoolExecutor(
|
|||
|
0, // 核心线程数 0(不保持任何核心线程)
|
|||
|
5, // 最大线程数为 4
|
|||
|
60L, // 空闲线程保持时间 60 秒
|
|||
|
TimeUnit.SECONDS, // 时间单位:秒
|
|||
|
new SynchronousQueue<>(),// 使用一个无界队列(任务等待队列)
|
|||
|
Executors.defaultThreadFactory(), // 使用默认线程工厂
|
|||
|
new ThreadPoolExecutor.AbortPolicy() // 默认的拒绝策略:抛出异常
|
|||
|
);
|
|||
|
|
|||
|
// 提交一些任务
|
|||
|
for (int i = 0; i < 10; i++) {
|
|||
|
final int taskId = i;
|
|||
|
executor.submit(() -> {
|
|||
|
System.out.println("Task " + taskId + " executed by: " + Thread.currentThread().getName());
|
|||
|
try {
|
|||
|
// 模拟任务执行时间
|
|||
|
Thread.sleep(1000);
|
|||
|
} catch (InterruptedException e) {
|
|||
|
e.printStackTrace();
|
|||
|
}
|
|||
|
});
|
|||
|
}
|
|||
|
|
|||
|
// 等待所有任务完成
|
|||
|
try {
|
|||
|
Thread.sleep(5000);
|
|||
|
} catch (InterruptedException e) {
|
|||
|
e.printStackTrace();
|
|||
|
}
|
|||
|
|
|||
|
// 关闭线程池
|
|||
|
executor.shutdown();
|
|||
|
}
|
|||
|
}
|