文章目录
四种线程池
- 顶级接口Executor,但不是线程池,知识一个执行线程的工具。
- 真正线程池接口时executorService。
ThreadPoolExecutor构造函数
1 | public ThreadPoolExecutor(int corePoolSize,//核心线程大小 |
1.newCachedThreadPool(重用-无限线程-一个大小队列,短时间的任务好)
对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。
- 调用 execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。
- 终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
core 0, max, sychronousQueue
1 | public static ExecutorService newCachedThreadPool() { |
2.newFixedThreadPool(可重用-固定线程数,无界队列)
core=max, linkedblockqueue
创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。
1 | public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { |
3.newScheduledThreadPool(延迟/定期执行,无线线程)
core, max, delayedworkqueue
1 | public ScheduledThreadPoolExecutor(int corePoolSize) { |
使用:
1 | ScheduledExecutorService scheduledThreadPool= Executors.newScheduledThreadPool(3); |
4.newSingleThreadExecutor(只有一个线程,无界队列)
core1, max1, linkedblockqueue
1 | public static ExecutorService newSingleThreadExecutor() { |