什么是线程池?怎么创建线程池?
线程池就是开辟一块内存空间,一次性创建出指定个数的线程放入线程池,当有任务来临时,从线程池中取一个线程为其提供服务,不用的时候就还回去。本质上是以空间换时间。
常见线程池的创建
- FixedThreadPool
使用Executors创建FixedThreadPool,对应构造方法
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
该方法采用的任务队列为linkedBlockingQueue,是无界阻塞队列,若有源源不断的任务添加到队列中,可能会耗尽内存,最终导致OOM(OutOfMemory)。
2. SingleThreadExcutor
使用Executors创建SingleThreadExcutor,对应构造方法
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
同样可能会造成OOM
- 除了可能会造成OOM之外,使用Executors创建线程也不能自定义线程名字,不利于排查问题
- 使用ThreadPoolExecutor自定义线程池,对应构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
使用ThreadPoolExecutor创建线程,指定工作队列大小,不会导致OOM。