1、Excutors工厂方式方式
ExecutorService executorService = Executors.newFixedThreadPool(10);
2、手动newThreadPoolExecutor方式
ThreadFactory threadFactory = Executors.defaultThreadFactory();
ThreadPoolExecutor tpe = new ThreadPoolExecutor(100, 200, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(300,true), threadFactory, new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (!executor.isShutdown()){
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
阿里:推荐我们用第二种,可以使程序员更加明白线程池的各个参数含义, 避免盲目使用oom,可以有自己的核心线程,最大线程数量的设置,也可以设置自己的拒绝策略