public class Demo01 {
public static void main(String[] args) {
//线程池的3大方法,7大参数,4大策略
// ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程
// ExecutorService threadPool = Executors.newFixedThreadPool(5);//创建一个固定大小为5的线程
// ExecutorService threadPool = Executors.newCachedThreadPool();//遇强则强
// 个人感觉还可以(自己写7大参数) ThreadPoolExecutor threadPool = new ThreadPoolExecutor
/*
* new ThreadPoolExecutor.DiscardPolicy(); //满了,不处理了,直接抛出异常(例如下面的最多是5+3)
* new ThreadPoolExecutor.DiscardOldestPolicy(); //哪里来的,回哪里
* new ThreadPoolExecutor.AbortPolicy(); //队列满了,丢掉任务,抛出异常
* new ThreadPoolExecutor.CallerRunsPolicy(); //队列满类,尝试和最早的竞争,不会抛出异常
*/
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
2, //核心线程数
5, //最大线程数
3, //存活时间
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3), //相当于等候厅
Executors.defaultThreadFactory(), //默认的
new ThreadPoolExecutor.DiscardPolicy() //拒绝策略
);
for (int i = 0; i < 9; i++) {
threadPool.execute(()->{
try {
System.out.println(Thread.currentThread().getName()+" 启动");
} catch (Exception e) {
e.printStackTrace();
}finally {
threadPool.shutdown();
}
});
}
}
}