❒ 在 Java 中,Executors 类提供了多种方法来创建线程池。以下是几种常见的创建线程池的方法:
1. 固定线程池(Fixed Thread Pool),这种线程池有固定数量的线程,适合于负载比较稳定的任务:
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(int nThreads);
2. 可缓存线程池(Cached Thread Pool),这种线程池会根据需要创建新线程,空闲的线程会在一段时间后被终止,适合于执行很多短期异步任务的场景:
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
3. 单线程池(Single Thread Pool),这种线程池只有一个线程执行任务,适合于需要保证任务顺序执行的场景:
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
4. 定时任务线程池(Scheduled Thread Pool),这种线程池可以用于定时或周期性地执行任务:
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(int corePoolSize);
5. 自定义线程池(ThreadPoolExecutor):
ThreadPoolExecutor customThreadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit unit, workQueue);
❒ 线程池不建议使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
✔ Fixed Thread Pool 和 Single Thread Pool: 允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
✔ CachedThreadPool: 允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。