日本黄色一级经典视频|伊人久久精品视频|亚洲黄色色周成人视频九九九|av免费网址黄色小短片|黄色Av无码亚洲成年人|亚洲1区2区3区无码|真人黄片免费观看|无码一级小说欧美日免费三级|日韩中文字幕91在线看|精品久久久无码中文字幕边打电话

當前位置:首頁 > 單片機 > 架構師社區(qū)
[導讀]來自:冰河技術? 前言 在Java的高并發(fā)領域,線程池一直是一個繞不開的話題。有些童鞋一直在使用線程池,但是,對于如何創(chuàng)建線程池僅僅停留在使用Executors工具類的方式,那么,創(chuàng)建線程池究竟存在哪幾種方式呢?就讓我們一起從創(chuàng)建線程池的源碼來深入分析究竟

高并發(fā)之——創(chuàng)建線程池居然有這么多方式...

來自:冰河技術 

前言

在Java的高并發(fā)領域,線程池一直是一個繞不開的話題。有些童鞋一直在使用線程池,但是,對于如何創(chuàng)建線程池僅僅停留在使用Executors工具類的方式,那么,創(chuàng)建線程池究竟存在哪幾種方式呢?就讓我們一起從創(chuàng)建線程池的源碼來深入分析究竟有哪些方式可以創(chuàng)建線程池。

使用Executors工具類創(chuàng)建線程池

在創(chuàng)建線程池時,初學者用的最多的就是Executors 這個工具類,而使用這個工具類創(chuàng)建線程池時非常簡單的,不需要關注太多的線程池細節(jié),只需要傳入必要的參數(shù)即可。Executors 工具類提供了幾種創(chuàng)建線程池的方法,如下所示。

  • Executors.newCachedThreadPool:創(chuàng)建一個可緩存的線程池,如果線程池的大小超過了需要,可以靈活回收空閑線程,如果沒有可回收線程,則新建線程

  • Executors.newFixedThreadPool:創(chuàng)建一個定長的線程池,可以控制線程的最大并發(fā)數(shù),超出的線程會在隊列中等待

  • Executors.newScheduledThreadPool:創(chuàng)建一個定長的線程池,支持定時、周期性的任務執(zhí)行

  • Executors.newSingleThreadExecutor: 創(chuàng)建一個單線程化的線程池,使用一個唯一的工作線程執(zhí)行任務,保證所有任務按照指定順序(先入先出或者優(yōu)先級)執(zhí)行

  • Executors.newSingleThreadScheduledExecutor:創(chuàng)建一個單線程化的線程池,支持定時、周期性的任務執(zhí)行

  • Executors.newWorkStealingPool:創(chuàng)建一個具有并行級別的work-stealing線程池

其中,Executors.newWorkStealingPool方法是Java 8中新增的創(chuàng)建線程池的方法,它能夠為線程池設置并行級別,具有更高的并發(fā)度和性能。除了此方法外,其他創(chuàng)建線程池的方法本質(zhì)上調(diào)用的是ThreadPoolExecutor類的構造方法。

例如,我們可以使用如下代碼創(chuàng)建線程池。

Executors.newWorkStealingPool();
Executors.newCachedThreadPool();
Executors.newScheduledThreadPool(3);

使用ThreadPoolExecutor類創(chuàng)建線程池

從代碼結構上看ThreadPoolExecutor類繼承自AbstractExecutorService,也就是說,ThreadPoolExecutor類具有AbstractExecutorService類的全部功能。

既然Executors工具類中創(chuàng)建線程池大部分調(diào)用的都是ThreadPoolExecutor類的構造方法,所以,我們也可以直接調(diào)用ThreadPoolExecutor類的構造方法來創(chuàng)建線程池,而不再使用Executors工具類。接下來,我們一起看下ThreadPoolExecutor類的構造方法。

ThreadPoolExecutor類中的所有構造方法如下所示。

public ThreadPoolExecutor(int corePoolSize,
                  int maximumPoolSize,
                  long keepAliveTime,
                  TimeUnit unit,
                 BlockingQueue<Runnable> workQueue
{
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}

public ThreadPoolExecutor(int corePoolSize,
                int maximumPoolSize,
                long keepAliveTime,
                TimeUnit unit,
                BlockingQueue<Runnable> workQueue,
                    ThreadFactory threadFactory
{
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
     threadFactory, defaultHandler);
}

public ThreadPoolExecutor(int corePoolSize,
                int maximumPoolSize,
                long keepAliveTime,
                    TimeUnit unit,
                BlockingQueue<Runnable> workQueue,
                RejectedExecutionHandler handler
{
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
     Executors.defaultThreadFactory(), handler);
}

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.acc = System.getSecurityManager() == null ?
            null :
            AccessController.getContext();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

由ThreadPoolExecutor類的構造方法的源代碼可知,創(chuàng)建線程池最終調(diào)用的構造方法如下。

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.acc = System.getSecurityManager() == null ?
            null :
            AccessController.getContext();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

關于此構造方法中各參數(shù)的含義和作用,各位可以移步《高并發(fā)之——不得不說的線程池與ThreadPoolExecutor類淺析》進行查閱。

大家可以自行調(diào)用ThreadPoolExecutor類的構造方法來創(chuàng)建線程池。例如,我們可以使用如下形式創(chuàng)建線程池。

new ThreadPoolExecutor(0Integer.MAX_VALUE,
                       60L, TimeUnit.SECONDS,
                       new SynchronousQueue<Runnable>());

使用ForkJoinPool類創(chuàng)建線程池

在Java8的Executors工具類中,新增了如下創(chuàng)建線程池的方式。

public static ExecutorService newWorkStealingPool(int parallelism{
    return new ForkJoinPool
        (parallelism,
         ForkJoinPool.defaultForkJoinWorkerThreadFactory,
         nulltrue);
}

public static ExecutorService newWorkStealingPool({
    return new ForkJoinPool
        (Runtime.getRuntime().availableProcessors(),
         ForkJoinPool.defaultForkJoinWorkerThreadFactory,
         nulltrue);
}

從源代碼可以可以,本質(zhì)上調(diào)用的是ForkJoinPool類的構造方法類創(chuàng)建線程池,而從代碼結構上來看ForkJoinPool類繼承自AbstractExecutorService抽象類。接下來,我們看下ForkJoinPool類的構造方法。

public ForkJoinPool() {
    this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
         defaultForkJoinWorkerThreadFactory, nullfalse);
}
 public ForkJoinPool(int parallelism) {
    this(parallelism, defaultForkJoinWorkerThreadFactory, nullfalse);
}

public ForkJoinPool(int parallelism,
                ForkJoinWorkerThreadFactory factory,
                UncaughtExceptionHandler handler,
                boolean asyncMode)
 
{
    this(checkParallelism(parallelism),
         checkFactory(factory),
         handler,
         asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
         "ForkJoinPool-" + nextPoolId() + "-worker-");
    checkPermission();
}

private ForkJoinPool(int parallelism,
                 ForkJoinWorkerThreadFactory factory,
                 UncaughtExceptionHandler handler,
                 int mode,
                 String workerNamePrefix)
 
{
    this.workerNamePrefix = workerNamePrefix;
    this.factory = factory;
    this.ueh = handler;
    this.config = (parallelism & SMASK) | mode;
    long np = (long)(-parallelism); // offset ctl counts
    this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
}

通過查看源代碼得知,F(xiàn)orkJoinPool的構造方法,最終調(diào)用的是如下私有構造方法。

private ForkJoinPool(int parallelism,
                 ForkJoinWorkerThreadFactory factory,
                 UncaughtExceptionHandler handler,
                 int mode,
                 String workerNamePrefix)
 
{
    this.workerNamePrefix = workerNamePrefix;
    this.factory = factory;
    this.ueh = handler;
    this.config = (parallelism & SMASK) | mode;
    long np = (long)(-parallelism); // offset ctl counts
    this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
}

其中,各參數(shù)的含義如下所示。

  • parallelism:并發(fā)級別。

  • factory:創(chuàng)建線程的工廠類對象。

  • handler:當線程池中的線程拋出未捕獲的異常時,統(tǒng)一使用UncaughtExceptionHandler對象處理。

  • mode:取值為FIFO_QUEUE或者LIFO_QUEUE。

  • workerNamePrefix:執(zhí)行任務的線程名稱的前綴。

當然,私有構造方法雖然是參數(shù)最多的一個方法,但是其不會直接對外方法,我們可以使用如下方式創(chuàng)建線程池。

new ForkJoinPool();
new ForkJoinPool(Runtime.getRuntime().availableProcessors());
new ForkJoinPool(Runtime.getRuntime().availableProcessors(),
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             nulltrue);

使用ScheduledThreadPoolExecutor類創(chuàng)建線程池

在Executors工具類中存在如下方法類創(chuàng)建線程池。

public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
    return new DelegatedScheduledExecutorService
        (new ScheduledThreadPoolExecutor(1));
}

public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
    return new DelegatedScheduledExecutorService
        (new ScheduledThreadPoolExecutor(1, threadFactory));
}

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

public static ScheduledExecutorService newScheduledThreadPool(
        int corePoolSize, ThreadFactory threadFactory)
 
{
    return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}

從源碼來看,這幾個方法本質(zhì)上調(diào)用的都是ScheduledThreadPoolExecutor類的構造方法,ScheduledThreadPoolExecutor中存在的構造方法如下所示。

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue());
}

public ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue(), threadFactory);
}

public ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue(), handler);
}

public ScheduledThreadPoolExecutor(int corePoolSize,ThreadFactory threadFactory, RejectedExecutionHandler handler) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue(), threadFactory, handler);
}

而從代碼結構上看,ScheduledThreadPoolExecutor類繼承自ThreadPoolExecutor類,本質(zhì)上還是調(diào)用ThreadPoolExecutor類的構造方法,只不過此時傳遞的隊列為DelayedWorkQueue。我們可以直接調(diào)用ScheduledThreadPoolExecutor類的構造方法來創(chuàng)建線程池,例如以如下形式創(chuàng)建線程池。

new ScheduledThreadPoolExecutor(3)

最后,需要注意的是:ScheduledThreadPoolExecutor主要用來創(chuàng)建執(zhí)行定時任務的線程池

后記:

記?。?/span>你比別人強的地方,不是你做過多少年的CRUD工作,而是你比別人掌握了更多深入的技能。不要總停留在CRUD的表面工作,理解并掌握底層原理并熟悉源碼實現(xiàn),并形成自己的抽象思維能力,做到靈活運用,才是你突破瓶頸,脫穎而出的重要方向!

最后,作為一名合格(發(fā)際線比較高)的開發(fā)人員或者資深(禿頂)的工程師和架構師來說,理解原理和掌握源碼,并形成自己的抽象思維能力,靈活運用是你必須掌握的技能。

特別推薦一個分享架構+算法的優(yōu)質(zhì)內(nèi)容,還沒關注的小伙伴,可以長按關注一下:

高并發(fā)之——創(chuàng)建線程池居然有這么多方式...

長按訂閱更多精彩▼

高并發(fā)之——創(chuàng)建線程池居然有這么多方式...

如有收獲,點個在看,誠摯感謝

免責聲明:本文內(nèi)容由21ic獲得授權后發(fā)布,版權歸原作者所有,本平臺僅提供信息存儲服務。文章僅代表作者個人觀點,不代表本平臺立場,如有問題,請聯(lián)系我們,謝謝!

本站聲明: 本文章由作者或相關機構授權發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點,本站亦不保證或承諾內(nèi)容真實性等。需要轉載請聯(lián)系該專欄作者,如若文章內(nèi)容侵犯您的權益,請及時聯(lián)系本站刪除。
換一批
延伸閱讀

LED驅動電源的輸入包括高壓工頻交流(即市電)、低壓直流、高壓直流、低壓高頻交流(如電子變壓器的輸出)等。

關鍵字: 驅動電源

在工業(yè)自動化蓬勃發(fā)展的當下,工業(yè)電機作為核心動力設備,其驅動電源的性能直接關系到整個系統(tǒng)的穩(wěn)定性和可靠性。其中,反電動勢抑制與過流保護是驅動電源設計中至關重要的兩個環(huán)節(jié),集成化方案的設計成為提升電機驅動性能的關鍵。

關鍵字: 工業(yè)電機 驅動電源

LED 驅動電源作為 LED 照明系統(tǒng)的 “心臟”,其穩(wěn)定性直接決定了整個照明設備的使用壽命。然而,在實際應用中,LED 驅動電源易損壞的問題卻十分常見,不僅增加了維護成本,還影響了用戶體驗。要解決這一問題,需從設計、生...

關鍵字: 驅動電源 照明系統(tǒng) 散熱

根據(jù)LED驅動電源的公式,電感內(nèi)電流波動大小和電感值成反比,輸出紋波和輸出電容值成反比。所以加大電感值和輸出電容值可以減小紋波。

關鍵字: LED 設計 驅動電源

電動汽車(EV)作為新能源汽車的重要代表,正逐漸成為全球汽車產(chǎn)業(yè)的重要發(fā)展方向。電動汽車的核心技術之一是電機驅動控制系統(tǒng),而絕緣柵雙極型晶體管(IGBT)作為電機驅動系統(tǒng)中的關鍵元件,其性能直接影響到電動汽車的動力性能和...

關鍵字: 電動汽車 新能源 驅動電源

在現(xiàn)代城市建設中,街道及停車場照明作為基礎設施的重要組成部分,其質(zhì)量和效率直接關系到城市的公共安全、居民生活質(zhì)量和能源利用效率。隨著科技的進步,高亮度白光發(fā)光二極管(LED)因其獨特的優(yōu)勢逐漸取代傳統(tǒng)光源,成為大功率區(qū)域...

關鍵字: 發(fā)光二極管 驅動電源 LED

LED通用照明設計工程師會遇到許多挑戰(zhàn),如功率密度、功率因數(shù)校正(PFC)、空間受限和可靠性等。

關鍵字: LED 驅動電源 功率因數(shù)校正

在LED照明技術日益普及的今天,LED驅動電源的電磁干擾(EMI)問題成為了一個不可忽視的挑戰(zhàn)。電磁干擾不僅會影響LED燈具的正常工作,還可能對周圍電子設備造成不利影響,甚至引發(fā)系統(tǒng)故障。因此,采取有效的硬件措施來解決L...

關鍵字: LED照明技術 電磁干擾 驅動電源

開關電源具有效率高的特性,而且開關電源的變壓器體積比串聯(lián)穩(wěn)壓型電源的要小得多,電源電路比較整潔,整機重量也有所下降,所以,現(xiàn)在的LED驅動電源

關鍵字: LED 驅動電源 開關電源

LED驅動電源是把電源供應轉換為特定的電壓電流以驅動LED發(fā)光的電壓轉換器,通常情況下:LED驅動電源的輸入包括高壓工頻交流(即市電)、低壓直流、高壓直流、低壓高頻交流(如電子變壓器的輸出)等。

關鍵字: LED 隧道燈 驅動電源
關閉