1. 这3种创建线程池的方式有风险
- FixedThreadPool : 固定大小的线程池
- SingleThreadExecutor : 单个线程的线程池
- CachedThreadPool : 可缓存的线程池
- FixedThreadPool内部其实也是使用
ThreadPoolExecutor
来创建的
等价于 :
new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
会发现核心线程和最大线程数是一样的,以此铸就了固定大小的线程池。
使用FixedThreadPool
package LearnThreadPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
/**
* 使用固定大小的线程池
*
* @author cat
* @version 2025/2/24 20:09
* @since JDK17
*/
public class UseFixedThreadPool {
public static void m() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
// 创建一个大小为10的固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
IntStream.range(0, 3).forEach(i -> executorService.execute(new Thread(UseFixedThreadPool::m)));
executorService.shutdown();
}
}
输出 :
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
- SingleThreadExecutor内部其实也是使用
ThreadPoolExecutor
来创建的。
等价于 :
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
使用SingleThreadExecutor
package LearnThreadPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
/**
* 使用固定大小的线程池
*
* @author cat
* @version 2025/2/24 20:09
* @since JDK17
*/
public class UseFixedThreadPool {
public static void m() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
// 创建一个大小为10的固定大小的线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
IntStream.range(0, 3).forEach(i -> executorService.execute(new Thread(UseFixedThreadPool::m)));
executorService.shutdown();
}
}
输出 :
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
CachedThreadPool
内部其实也是使用ThreadPoolExecutor
来创建的。
new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
- FixedThreadPool 和 SingleThreadExecutor 允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 00M。
- CachedThreadPool 允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 00M。