Java線程池

線程池源碼

  • 1稀余、一般我們會(huì)直接使用Excutors創(chuàng)建線程池:

  • 2裳瘪、線程池的創(chuàng)建都會(huì)交給ThreadPoolExecutor(...)的構(gòu)造方法月幌,下面是參數(shù)最多的一個(gè)阅嘶。

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
    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ù):
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
  • 1.workQueue:被提交但未執(zhí)行的任務(wù)隊(duì)列,由于其類型為BlockingQueue<Runnable>接口 组民,限定了只能放Runnable類型棒仍。又因?yàn)樗羞@么多子類,因此可以使用不同的實(shí)現(xiàn)類臭胜,完成不同的策略莫其。

  • 2.threadFactory:線程工廠,用戶創(chuàng)建線程耸三,一般默認(rèn)就好榜配。

  • 3.拒絕策略:當(dāng)線程池中線程用完,并且等待隊(duì)列也已經(jīng)滿了吕晌,就會(huì)執(zhí)行拒絕策略蛋褥。


    image.png

ThreadPoolExecutor線程池核心調(diào)度代碼:

/**
     * Executes the given task sometime in the future.  The task
     * may execute in a new thread or in an existing pooled thread.
     *
     * If the task cannot be submitted for execution, either because this
     * executor has been shutdown or because its capacity has been reached,
     * the task is handled by the current {@code RejectedExecutionHandler}.
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }

因此調(diào)度邏輯可以總結(jié)為:

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市睛驳,隨后出現(xiàn)的幾起案子烙心,更是在濱河造成了極大的恐慌,老刑警劉巖乏沸,帶你破解...
    沈念sama閱讀 216,651評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件淫茵,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡蹬跃,警方通過(guò)查閱死者的電腦和手機(jī)匙瘪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蝶缀,“玉大人丹喻,你說(shuō)我怎么就攤上這事∥潭迹” “怎么了碍论?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,931評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)柄慰。 經(jīng)常有香客問(wèn)我鳍悠,道長(zhǎng),這世上最難降的妖魔是什么坐搔? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,218評(píng)論 1 292
  • 正文 為了忘掉前任藏研,我火速辦了婚禮,結(jié)果婚禮上概行,老公的妹妹穿的比我還像新娘蠢挡。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布袒哥。 她就那樣靜靜地躺著,像睡著了一般消略。 火紅的嫁衣襯著肌膚如雪堡称。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,198評(píng)論 1 299
  • 那天艺演,我揣著相機(jī)與錄音却紧,去河邊找鬼。 笑死胎撤,一個(gè)胖子當(dāng)著我的面吹牛晓殊,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播伤提,決...
    沈念sama閱讀 40,084評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼巫俺,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了肿男?” 一聲冷哼從身側(cè)響起介汹,我...
    開(kāi)封第一講書(shū)人閱讀 38,926評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎舶沛,沒(méi)想到半個(gè)月后嘹承,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,341評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡如庭,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評(píng)論 2 333
  • 正文 我和宋清朗相戀三年叹卷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坪它。...
    茶點(diǎn)故事閱讀 39,731評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡骤竹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出往毡,到底是詐尸還是另有隱情瘤载,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評(píng)論 5 343
  • 正文 年R本政府宣布卖擅,位于F島的核電站鸣奔,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏惩阶。R本人自食惡果不足惜挎狸,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望断楷。 院中可真熱鬧锨匆,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,676評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至土榴,卻和暖如春诀姚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背玷禽。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,829評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工赫段, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人矢赁。 一個(gè)月前我還...
    沈念sama閱讀 47,743評(píng)論 2 368
  • 正文 我出身青樓糯笙,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親撩银。 傳聞我的和親對(duì)象是個(gè)殘疾皇子给涕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 幾句閑扯:首先,我想說(shuō)java的線程池真的是很繞额获,以前一直都感覺(jué)新建幾個(gè)線程一直不退出到底是怎么實(shí)現(xiàn)的稠炬,也就有了后...
    一只小哈閱讀 81,506評(píng)論 24 202
  • 博客鏈接:http://www.ideabuffer.cn/2017/04/04/深入理解Java線程池:Thre...
    閃電是只貓閱讀 15,854評(píng)論 15 133
  • 我們的程序里,時(shí)常要使用多線程壮虫。因此多線程的管理變的尤為重要狈癞。ThreadPoolExecutor很好的解決了這一...
    非墨Zero閱讀 1,305評(píng)論 1 8
  • 作為一個(gè)程序員,平時(shí)關(guān)于線程也是使用的肯定很頻繁驻龟,舉個(gè)例子開(kāi)啟無(wú)數(shù)線程跑的同時(shí)就好像一個(gè)沒(méi)有紅綠燈的十字路口無(wú)數(shù)的...
    Mr_Ashin閱讀 970評(píng)論 0 0
  • 前言:線程是稀缺資源撤摸,如果被無(wú)限制的創(chuàng)建毅桃,不僅會(huì)消耗系統(tǒng)資源,還會(huì)降低系統(tǒng)的穩(wěn)定性准夷,合理的使用線程池對(duì)線程進(jìn)行統(tǒng)一...
    SDY_0656閱讀 716評(píng)論 0 1