jdk的内置拒绝策略:
创建线程必须使用线程池创建
线程池不允许使用Executors创建,因为线程最大数设置的是Integer.MAX_VALUE = 21E+,无线的创建线程可能造成OOM
使用ThreadPoolExecutor创建线程池:
# ThreadPoolExecutor
ExecutorService threadPool = new ThreadPoolExecutor(0, 10,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
# Executors
ExecutorService threadPool = Executors.newCachedThreadPool();
public static void main(String[] args) {
ExecutorService threadPool = new ThreadPoolExecutor(
2,// 线程核心数
5, // 最大线程数
1L, // 线程空闲时间
TimeUnit.SECONDS, // 时间单位
new LinkedBlockingDeque<Runnable>(3), // 阻塞队列,要设置队列大小,默认是Integer.MAX_VALUE
Executors.defaultThreadFactory(), // 线程工厂
new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
try {
for (int i = 0; i < 10; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e){
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
1、CPU密集型
CPU核数+1
Runtime.getRuntime().availableProcessors()+1
2、IO密集型
Runtime.getRuntime().availableProcessors() * 2