public synchronized ExecutorService executorService() {
if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
在 OkHttp
的分发器中的线程池定义如上,其实就和 Executors.newCachedThreadPool()
创建的线程一样,分析一下参数:
- 第一个参数:核心线程数(一直存在的线程数),为零表示线程池不会一直缓存线程;
- 第二个参数:最大线程数(多出的线程会被缓存);
- 第三个参数:最大缓存时间(线程池中的所有线程都是在60s内没有工作就会被回收);
- 第四个参数:缓存时间单位;
- 第五个参数:阻塞等待队列;
- 第六个参数:线程工厂(用于生产线程)。
当需要线程池执行任务时,有如下几种情况:
a. 当前线程数量小于核心线程数,将新建(核心)线程来处理被添加的任务;
b. 当前线程数量大于等于核心线程数,