Java高并发程序设计(六)--线程池(1)
線程的創(chuàng)建和關閉需要花費時間,可能會浪費資源,所以可以通過讓線程復用來解決這個問題。
線程池就是這樣一個概念,當需要創(chuàng)建線程的時候直接從線程池中獲取,當關閉線程的時候直接歸還線程給線程池。
ThreadPoolExecutor就是JDK提供的這樣一個類。
它繼承AbstructExecutorService類,AbstructExecutorService類實現(xiàn)ExecutorSerive接口,ExecutorSerive接口繼承Executor接口。
具體方法可以在API中自行查看。
看一下ThreadPoolExtcutor的構造方法:
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler) {if (corePoolSize < 0 ||maximumPoolSize <= 0 ||maximumPoolSize < corePoolSize ||keepAliveTime < 0)throw new IllegalArgumentException();if (workQueue == null || threadFactory == null || handler == null)throw new NullPointerException();this.corePoolSize = corePoolSize;this.maximumPoolSize = maximumPoolSize;this.workQueue = workQueue;this.keepAliveTime = unit.toNanos(keepAliveTime);this.threadFactory = threadFactory;this.handler = handler;}下面是對它參數(shù)的解釋:
corePoolSize:指定了線程池中線程的數(shù)量
maximumPoolSize:指定了線程池中線程的最大數(shù)量
keepAliveTime:當線程數(shù)量超過corePoolSize,多余線程的存活時間
TimeUnit:keepAliveTime的單位
workQueue:任務隊列,被提交但還沒執(zhí)行的任務
threadFactory:用于創(chuàng)建線程
Handler:線程太多的拒絕策略
線程池有四個構造函數(shù),其他三個只是把一些參數(shù)變成了默認而已,然后調用的這個構造函數(shù)。
對線程池類有點基本的了解之后接下來看看另一個類Extcutors。它是一個工廠類,可以從它獲得特定功能的線程池。
public static ExecutorService newFixedThreadPool(xxxxxxx)public static ExecutorService newSingleThreadExecutor(xxxx)?
public static ExecutorService newCachedThreadPool(xxxxx)
public static ScheduledExecutorService newSingleThreadScheduledExecutor(xxxx)
public static ScheduledExecutorService newScheduledThreadPool(xxxxx)
功能分別是獲得固定線程數(shù)目的線程池,獲得一個線程的線程池,獲得線程數(shù)量可變的線程池,獲得可在給定時間執(zhí)行的單線程池,獲得可在給定時間執(zhí)行的多線程池。
對于前三個來說,它們只是根據(jù)參數(shù)不同對ThreadPoolExecutor進行了封裝。
而ScheduledExecutorService則是繼承自ExecutorService,又在它的基礎上添加了一些功能。
寫個小例子:
public class demo implements Runnable{public static void main(String[] args) {ExecutorService es=Executors.newFixedThreadPool(2);for(int i=0;i<10;i++){es.submit(new Thread(new demo()));}}public void run() {System.out.println(System.currentTimeMillis());try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}} }獲得一個數(shù)量為2的固定線程數(shù)量線程池,在run里面每個線程sleep兩秒,結果如下
可以清楚地看到每兩秒后兩個線程被執(zhí)行。
線程的邏輯調度如下:
?
當線程池滿,隊列也滿的時候,會采用拒絕策略,JDK提供了四種內置拒絕策略在線程池類里面:
具體的可以自行查找相關資料。
自此告一段落,線程池還有很多內容沒有總結,后續(xù)再總結吧。
轉載于:https://www.cnblogs.com/blogofjzq/p/9405773.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結
以上是生活随笔為你收集整理的Java高并发程序设计(六)--线程池(1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bzoj3895: 取石子(博弈论,记忆
- 下一篇: Java 字符串拼接 StringBui