newFixedThreadPool原理

@(Executors)[newFixedThreadPool]

[TOC]

java線程池

在面向?qū)ο缶幊讨腥战茫瑒?chuàng)建和銷毀對象是很費時間的庭呜,因為創(chuàng)建一個對象要獲取內(nèi)存資源或者其它更多資源。在Java中更是如此钢颂,虛擬機將試圖跟蹤每一個對象钞它,以便能夠在對象銷毀后進行垃圾回收拜银。所以提高服務(wù)程序效率的一個手段就是盡可能減少創(chuàng)建和銷毀對象的次數(shù)殊鞭,特別是一些很耗資源的對象創(chuàng)建和銷毀。如何利用已有對象來服務(wù)就是一個需要解決的關(guān)鍵問題尼桶,其實這就是一些"池化資源"技術(shù)產(chǎn)生的原因操灿。

newFixedPool作用

創(chuàng)建一個固定線程數(shù)的線程池,在任何時候最多只有nThreads個線程被創(chuàng)建泵督。如果在所有線程都處于活動狀態(tài)時趾盐,有其他任務(wù)提交,他們將等待隊列中直到線程可用小腊。如果任何線程由于執(zhí)行過程中的故障而終止救鲤,將會有一個新線程將取代這個線程執(zhí)行后續(xù)任務(wù)。

構(gòu)造方法

newFixedPool擁有兩個構(gòu)造方法:

參數(shù)為nThreads的構(gòu)造方法:

 public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

構(gòu)造方法中的nThreads代表固定線程池中的線程數(shù)秩冈,當使用此構(gòu)造方法創(chuàng)建線程池后本缠,就會創(chuàng)建nThreads個線程在線程池內(nèi)。
參數(shù)為: nThreads,ThreadFactory的構(gòu)造方法:

  public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }

ThreadPoolExecutor構(gòu)造方法

newFixedThreadPool(int nThreads) 使用的構(gòu)造方法:

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

此ThreadPoolExecutor構(gòu)造方法的參數(shù)有5個:
corePoolSize:線程池中所保存的線程數(shù)入问,包括空閑線程丹锹,newFixedThreadPool中傳入nThreads
maximumPoolSize:池中允許的最大線程數(shù),newFixedThreadPool中傳入nThreads芬失,使線程池的最大線程數(shù)與線程池中保存的線程數(shù)一致楣黍,使保證線程池的線程數(shù)是固定的
TimeUnit:參數(shù)的時間單位
keepAliveTime:當線程數(shù)大于corePoolSize時,此為終止前多余的空閑線程等待新任務(wù)的最長時間
LinkedBlockingQueue workQueuqe:當任務(wù)被執(zhí)行前棱烂,放到此阻塞隊列中租漂,任務(wù)將被放在阻塞隊列中直到使用execute方法提交Runnable任務(wù),不同的線程池主要是這個參數(shù)的不通,比如scheduledThreadPoolExecutor這邊使用的就是DelayedWorkQueue這個隊列

**注意:
* The queue used for holding tasks and handing off to worker
* threads. We do not require that workQueue.poll() returning
* null necessarily means that workQueue.isEmpty(), so rely
* solely on isEmpty to see if the queue is empty (which we must
* do for example when deciding whether to transition from
* SHUTDOWN to TIDYING). This accommodates special-purpose
* queues such as DelayQueues for which poll() is allowed to
* return null even if it may later return non-null when delays
* expire.
*/

    private final BlockingQueue<Runnable> workQueue;

newFixedThreadPool(in nThreads,ThreadFactory threadFactory)使用的構(gòu)造方法:

 public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);   //創(chuàng)建默認線程工廠,并設(shè)置駁回的異常處理
    }

創(chuàng)建ThreadPoolExecutor時傳入Executors.defaultThreadFactory()這個默認線程工廠實例窜锯。
在代碼中調(diào)用ThreadPoolExecutor中的內(nèi)部類DefaultThreadFactory工廠张肾,在包中的注釋是這么寫的:threadFactory the factory to use when the executor creates a new thread 。這是用來使用executor創(chuàng)建新線程的工廠锚扎。

static class DefaultThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    DefaultThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                              Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" +
                      poolNumber.getAndIncrement() +
                     "-thread-";
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                              namePrefix + threadNumber.getAndIncrement(),
                              0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}

調(diào)用DefaultThreadFactory的構(gòu)造方法初始化線程組和生成線程前綴吞瞪。在創(chuàng)建完線程工廠后,需要使用線程工廠來創(chuàng)建線程并啟動驾孔。

使用線程池中的線程執(zhí)行Runnable任務(wù)

當之前的初始化(corePoolSize等于maxiumPoolSize等于nThreads芍秆,并創(chuàng)建defaultThreadFactory)就可以運行定義好的線程了。
執(zhí)行線程的代碼如下:

    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);
    }

其中最重要的方法是addWorker翠勉,其方法目的是創(chuàng)建Worker對象妖啥,并將Worker對象加入到HashSet<Worker> workers中。在加入workers之前对碌,先創(chuàng)建ReentrantLock排它鎖荆虱,將worker同步的加入到workers中。當worker成功被加入后朽们,啟動本次放入set中的線程怀读。

  private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                c = ctl.get();  // Re-read ctl
                if (runStateOf(c) != rs)
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
        }

        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    // Recheck while holding lock.
                    // Back out on ThreadFactory failure or if
                    // shut down before lock acquired.
                    int rs = runStateOf(ctl.get());

                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

Worker對象的構(gòu)造方法:

Worker(Runnable firstTask) {
    setState(-1); // inhibit interrupts until runWorker
    this.firstTask = firstTask;
    this.thread = getThreadFactory().newThread(this);
}

通過線程工廠 來創(chuàng)建線程。

 public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                              namePrefix + threadNumber.getAndIncrement(),
                              0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末骑脱,一起剝皮案震驚了整個濱河市菜枷,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌叁丧,老刑警劉巖啤誊,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異拥娄,居然都是意外死亡蚊锹,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門稚瘾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來牡昆,“玉大人,你說我怎么就攤上這事孟抗∏ㄑ睿” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵凄硼,是天一觀的道長铅协。 經(jīng)常有香客問我,道長摊沉,這世上最難降的妖魔是什么狐史? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上骏全,老公的妹妹穿的比我還像新娘苍柏。我一直安慰自己,他們只是感情好姜贡,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布试吁。 她就那樣靜靜地躺著,像睡著了一般楼咳。 火紅的嫁衣襯著肌膚如雪熄捍。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天母怜,我揣著相機與錄音余耽,去河邊找鬼。 笑死苹熏,一個胖子當著我的面吹牛碟贾,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播轨域,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼袱耽,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了疙挺?” 一聲冷哼從身側(cè)響起扛邑,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤怜浅,失蹤者是張志新(化名)和其女友劉穎铐然,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體恶座,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡搀暑,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了跨琳。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片自点。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖脉让,靈堂內(nèi)的尸體忽然破棺而出桂敛,到底是詐尸還是另有隱情,我是刑警寧澤溅潜,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布术唬,位于F島的核電站,受9級特大地震影響滚澜,放射性物質(zhì)發(fā)生泄漏粗仓。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望借浊。 院中可真熱鬧塘淑,春花似錦、人聲如沸蚂斤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽曙蒸。三九已至召噩,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間逸爵,已是汗流浹背具滴。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留师倔,地道東北人构韵。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像趋艘,于是被迫代替她去往敵國和親疲恢。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353

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