一、幾個比較重要的類
1.Executor接口:線程池的根接口。
2.ExecutorService接口:繼承Executor,線程池常見操作接口。
3.ScheduledExecutorService接口:繼承ExecutorService,添加了重復執(zhí)行任務的操作。
4.ThreadPoolExecutor類:ExecutorService的默認實現(xiàn)。
5.ScheduledThreadPoolExecutor類:繼承ThreadPoolExecutor類,并實現(xiàn)ScheduledExecutorService接口,是周期性任務調(diào)度的類實現(xiàn)。
二、Java通過Executors類提供四種線程池,分別為:
1.newCachedThreadPool
創(chuàng)建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。 該類返回ThreadPoolExecutor實例,corePoolSize為0;maximumPoolSize為Integer.MAX_VALUE;keepAliveTime為60L;unit為TimeUnit.SECONDS;workQueue為SynchronousQueue(同步隊列)。
2.newFixedThreadPool
創(chuàng)建一個定長線程池,可控制線程最大并發(fā)數(shù),超出的線程會在隊列中等待。 該類返回ThreadPoolExecutor實例,接收參數(shù)為所設定線程數(shù)量nThread,corePoolSize為nThread,maximumPoolSize為nThread;keepAliveTime為0L(不限時);unit為:TimeUnit.MILLISECONDS;WorkQueue為:new LinkedBlockingQueue<Runnable>() 無界阻塞隊列。
3.newScheduledThreadPool
創(chuàng)建一個定長線程池,支持定時及周期性任務執(zhí)行。 FinalizableDelegatedExecutorService包裝的ThreadPoolExecutor實例,corePoolSize為1;maximumPoolSize為1;keepAliveTime為0L;unit為:TimeUnit.MILLISECONDS;workQueue為:new LinkedBlockingQueue<Runnable>() 無界阻塞隊列。
4.newSingleThreadExecutor
創(chuàng)建一個單線程化的線程池,它只會用唯一的工作線程來執(zhí)行任務,保證所有任務按照指定順序(FIFO, LIFO, 優(yōu)先級)執(zhí)行。創(chuàng)建ScheduledThreadPoolExecutor實例,corePoolSize為傳遞來的參數(shù),maximumPoolSize為Integer.MAX_VALUE;keepAliveTime為0;unit為:TimeUnit.NANOSECONDS;workQueue為:new DelayedWorkQueue() 一個按超時時間升序排序的隊列。
備注:有的代碼規(guī)范推薦用ThreadPoolExecutor手工創(chuàng)建線程池,而不是用Executors提供的線程池工具去創(chuàng)建,因為最大線程數(shù)為Integer.MAX_VALUE的線程池工具,因為可能會導致OOM。
參考鏈接:
自定義線程池內(nèi)置線程池的使用 ThreadPoolExecutor和Executorservice 示例與注意事項 https://blog.csdn.net/qq_41358574/article/details/121852746
ExecutorService和ThreadPoolExecutor https://blog.csdn.net/qq_36898043/article/details/79732711
并發(fā)隊列之無界阻塞隊列LinkedBlockingQueue https://blog.csdn.net/weixin_38192427/article/details/117262033
Java四種線程池使用 https://blog.csdn.net/achuo/article/details/80623893
Java線程池種類、區(qū)別和適用場景 https://blog.csdn.net/w05980598/article/details/79425071