简介
SingleThreadPool是使用单个工作线程的线程池。
创建方法
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
corePoolSize和maximumPoolSize都是1,即SingleThreadPool只有一个核心线程。其他参数都和FixedThreadPool一样。
execute方法执行
执行execute方法时,若当前运行的线程数未达到核心线程数(没有正在运行的线程),就创建一个新线程来处理任务;如果当前有运行的线程,就把任务添加到阻塞队列LinkedBlockingQueue。SingleThreadPool能够确保所有的任务都在一个线程中按照顺序逐一执行。