MultiThread/multithreading/src/main/java/thead/pool/ThreadPoolNewCached03Custom...

47 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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();
}
}