學習筆記(09):Java併發編程精講-Executors中常用的幾種線程池介紹和區別

一、常見線程池:

1. 固定線程數量的線程池

    i. 通過Executors.newFixedThreadPool 來創建

    ii. 核心線程數和最大線程數一樣

    iii. 達到核心線程數後,空閒線程不會超時被終止或釋放。

    iiii. 每添加一個任務後,會將任務添加到工作任務列隊列,線程池創建一個線程,線程數等於核心線程數時,就不會再創建線程。

2. 單線程的線程池

    i 通過 Executors.newSingelThreadExecutor 來創建。

    ii. 核心線程數和最大線程數一樣,且均爲 1 ,也就是隻有一個線程在執行隊列的工作任務。

    iii. 使用了代理模式來創建線程池。

3. 可緩存的線程池

    i 通過 Executors.newCachedThreadPool 來創建

    ii. 核心線程數爲 0 ,最大線程數爲無限大(實際是 int 最大值),空閒線程可以緩存 60s,空閒超過60s的線程會被回收。

    iii. 使用了 SynchronousQueue 同步隊列,添加任務的同時,需有工作線程來取任務纔可完成任務的添加和執行。

4. 定時執行的線程池

    i. 通過 Executors.newScheduledThreadPool 來創建

    ii. 可指定核心線程數,最大線程數爲無限大(實際是 int 最大值),核心線程數空閒不會超過被回收。

    iii. 使用了 DelayedWorkQueue 延時隊列,通過延時隊列來控制時間來執行

二、  線程執行源碼解釋:

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

execute 底層執行過程:

1. 檢查線程池的運行狀態和工作線程數量,如果工作線程數 < 核心線程數,則會創建一個新的線程來執行給定任務(調用addWorker來執行任務)

2. 如果超過了核心線程數,把任務放到工作隊列中,若工作隊列沒有滿,則添加任務後,仍檢查一下線程池狀態,如果沒有繼續運行(不是RUNNING狀態)就把任務移除,使用拒絕策略來處理當前任務;否則將創建或喚醒工作線程來執行任務

3. 線程池非RUNNING狀態或添加任務失敗後,使用拒絕策略來處理當前任務

 

addWorker 源碼分析:

/**
     * Checks if a new worker can be added with respect to current
     * pool state and the given bound (either core or maximum). If so,
     * the worker count is adjusted accordingly, and, if possible, a
     * new worker is created and started, running firstTask as its
     * first task. This method returns false if the pool is stopped or
     * eligible to shut down. It also returns false if the thread
     * factory fails to create a thread when asked.  If the thread
     * creation fails, either due to the thread factory returning
     * null, or due to an exception (typically OutOfMemoryError in
     * Thread.start()), we roll back cleanly.
     *
     * @param firstTask the task the new thread should run first (or
     * null if none). Workers are created with an initial first task
     * (in method execute()) to bypass queuing when there are fewer
     * than corePoolSize threads (in which case we always start one),
     * or when the queue is full (in which case we must bypass queue).
     * Initially idle threads are usually created via
     * prestartCoreThread or to replace other dying workers.
     *
     * @param core if true use corePoolSize as bound, else
     * maximumPoolSize. (A boolean indicator is used here rather than a
     * value to ensure reads of fresh values after checking other pool
     * state).
     * @return true if successful
     */
    private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            // 1. 檢查狀態
            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 {
            // 創建 worker(AQS)
            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;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章