package com.example.juc;
import java.util.concurrent.*;
/**
* @program: demo
* @description: 线程池
* @author: ZCY
**/
public class ThreadPoolDemo {
public static void main(String[] args) {
//本质都是调用ThreadPoolExecutor 三大方法,7大参数,4种策略
ExecutorService threadPool = null;
ExecutorService threadPool2 = null;
ExecutorService threadPool3 = null;
try {
threadPool = Executors.newCachedThreadPool(); //大小可变
threadPool2 = Executors.newSingleThreadExecutor();//只有一个核心线程
threadPool3 = Executors.newFixedThreadPool(5);//固定线程数
for (int i = 1; i <= 6; i++) {
threadPool3.execute(() -> {
System.out.println(Thread.currentThread().getName() + "---OK");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool3.shutdown();
}
}
}
class ThreadPoolDemo2 {
public static void main(String[] args) {
//自定义创建线程池
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
2, //核心线程数
5, //最大线程数
10, //超时时间
TimeUnit.SECONDS, //超时单位
new ArrayBlockingQueue<>(4), //阻塞队列
Executors.defaultThreadFactory(), //线程工厂
new ThreadPoolExecutor.CallerRunsPolicy() //拒绝策略
);
//四种拒绝策略
//ThreadPoolExecutor.AbortPolicy() 抛出异常
//ThreadPoolExecutor.DiscardPolicy() 不抛出异常,直接放弃任务
//ThreadPoolExecutor.DiscardOldestPolicy() 不抛出异常,将队列首的任务放弃,加入新任务
//ThreadPoolExecutor.CallerRunsPolicy() 请求从哪里来回哪里去 由main线程执行
//RejectedExecutionException
for (int i = 0; i < 9; i++) {
poolExecutor.execute(() -> {
System.out.println(Thread.currentThread().getName() + "--OK");
});
//System.out.println(Thread.activeCount());
//System.out.println("------------------");
}
poolExecutor.shutdown();
//最大线程如何定义
//System.out.println(Runtime.getRuntime().availableProcessors());
}
}
深入理解线程池
最新推荐文章于 2024-10-06 20:29:51 发布