不要用Excutors定义线程池,用ThreadPoolExcutor自定义
public class ExcutorDemo {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newFixedThreadPool(20);//一池20个线程
//ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池一个线程
//ExecutorService threadPool = Executors.newCachedThreadPool();//一池n个线程
//自定义线程池
ExecutorService threadPool = new ThreadPoolExecutor(
2,
10,
100L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(4),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
try {
for (int i = 0; i < 30; i++) {
threadPool.execute(() -> {
System.out.println("线程开启 "+Thread.currentThread().getName());
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
合理配置线程:
1.CPU密集型:高并发,任务执行时间短,一直告诉运行,线程池线程数一般设为cpu核数+1
2.IO密集型:a.IO密集型任务需要大量的IO,即大量的阻塞,尽可能配置多的线程数,如CPU核数*2+1
b.参考公式:CPU核数/(1-阻塞系数) 阻塞系数在0.8~0.9之间