Java自定義線程池相關(guān)代碼的介紹
創(chuàng)建Java自定義線程池的構(gòu)造方法很多,但是我們在使用中就會有以下幾個最主要的代碼應(yīng)用。我們在使用的時候就要先來了解下有關(guān)Java自定義線程池的源代碼。本例中參數(shù)的含義如下:
Java代碼
- ThreadPoolExecutor
- public ThreadPoolExecutor(int corePoolSize,
- int maximumPoolSize,
- long keepAliveTime,
- TimeUnit unit,
- BlockingQueue<Runnable> workQueue)
用給定的初始參數(shù)和默認(rèn)的線程工廠及處理程序創(chuàng)建新的 ThreadPoolExecutor。使用 Executors 工廠方法之一比使用此通用構(gòu)造方法方便得多。
參數(shù):
- corePoolSize - 池中所保存的線程數(shù),包括空閑線程。
- maximumPoolSize - 池中允許的***線程數(shù)。
- keepAliveTime - 當(dāng)線程數(shù)大于核心時,此為終止前多余的空閑線程
等待新任務(wù)的最長時間。- unit - keepAliveTime 參數(shù)的時間單位。
- workQueue - 執(zhí)行前用于保持任務(wù)的隊列。此隊列僅保持由 execute
方法提交的 Runnable 任務(wù)。
拋出:
IllegalArgumentException - 如果 corePoolSize 或 keepAliveTime 小于零,或者 maximumPoolSize 小于或等于零,或者 corePoolSize 大于 maximumPoolSize。
NullPointerException - 如果 workQueue 為 null
- ThreadPoolExecutor
- public ThreadPoolExecutor(int corePoolSize,
- int maximumPoolSize,
- long keepAliveTime,
- TimeUnit unit,
- BlockingQueue<Runnable> workQueue)
用給定的初始參數(shù)和默認(rèn)的線程工廠及處理程序創(chuàng)建新的 ThreadPoolExecutor。使用 Executors 工廠方法之一比使用此通用構(gòu)造方法方便得多。
參數(shù):
- corePoolSize - 池中所保存的線程數(shù),包括空閑線程。
- maximumPoolSize - 池中允許的***線程數(shù)。
- keepAliveTime - 當(dāng)線程數(shù)大于核心時,此為終止前多余的空閑
線程等待新任務(wù)的最長時間。- unit - keepAliveTime 參數(shù)的時間單位。
- workQueue - 執(zhí)行前用于保持任務(wù)的隊列。此隊列僅保持由 execute
方法提交的 Runnable 任務(wù)。- 拋出:
- IllegalArgumentException - 如果 corePoolSize 或
keepAliveTime 小于零,或者 maximumPoolSize 小于或等于零,
或者 corePoolSize 大于 maximumPoolSize。- NullPointerException - 如果 workQueue 為 null
Java自定義線程池稍微麻煩些,不過通過創(chuàng)建的ThreadPoolExecutor線程池對象,可以獲取到當(dāng)前線程池的尺寸、正在執(zhí)行任務(wù)的線程數(shù)、工作隊列等等。
【編輯推薦】