成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

ThreadPool實現(xiàn)原理

spacewander / 1757人閱讀

摘要:所以,并不代表線程池就一定立即就能退出,它也可能必須要等待所有正在執(zhí)行的任務(wù)都執(zhí)行完成了才能退出。

本文主要分析java.util.concurrent.ThreadPoolExecutor的實現(xiàn)原理,首先看它的構(gòu)造函數(shù):

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue 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;
}

corePoolSize:線程池中穩(wěn)定保存的線程數(shù)(一開始會小于這個數(shù))

maximumPoolSize:線程池中最大線程數(shù)

keepAliveTime and unit:大于最小線程數(shù)的線程空閑后存活時間

workQueue:用于存放任務(wù)的阻塞隊列

threadFactory:用于創(chuàng)建線程的工廠類

handler:當(dāng)任務(wù)隊列滿了且線程數(shù)達(dá)到了最大時的飽和策略

對于IO密集型任務(wù),線程數(shù)一般設(shè)為CPU數(shù)*2,對于計算密集型任務(wù),線程數(shù)一般設(shè)為CPU數(shù)。

當(dāng)調(diào)用execute方法時:

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

其流程如圖:

創(chuàng)建線程是通過addWorker創(chuàng)建內(nèi)部Worker類,其中調(diào)用getThreadFactory().newThread(this)來創(chuàng)建執(zhí)行自己的線程,之后在addWorker中start該線程,執(zhí)行Worker run方法中的runWorker會不斷的從任務(wù)隊列中獲取任務(wù)或阻塞,并且每次執(zhí)行任務(wù)前會執(zhí)行beforeExecute,之后會afterExecute,可以通過重寫beforeExecute方法來給執(zhí)行線程重命名。

線程池狀態(tài)變化如圖:

RUNNING: Accept new tasks and process queued tasks

SHUTDOWN: Don"t accept new tasks, but process queued tasks

STOP: Don"t accept new tasks, don"t process queued tasks, and interrupt in-progress tasks

TIDYING: All tasks have terminated, workerCount is zero, the thread transitioning to state TIDYING will run the terminated() hook method

TERMINATED: terminated() has completed

shutdownNow終止線程的方法是通過調(diào)用Thread.interrupt()方法來實現(xiàn)的:

 * 

If this thread is blocked in an invocation of the {@link * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link * Object#wait(long, int) wait(long, int)} methods of the {@link Object} * class, or of the {@link #join()}, {@link #join(long)}, {@link * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)}, * methods of this class, then its interrupt status will be cleared and it * will receive an {@link InterruptedException}. * *

If this thread is blocked in an I/O operation upon an {@link * java.nio.channels.InterruptibleChannel InterruptibleChannel} * then the channel will be closed, the thread"s interrupt * status will be set, and the thread will receive a {@link * java.nio.channels.ClosedByInterruptException}. * *

If this thread is blocked in a {@link java.nio.channels.Selector} * then the thread"s interrupt status will be set and it will return * immediately from the selection operation, possibly with a non-zero * value, just as if the selector"s {@link * java.nio.channels.Selector#wakeup wakeup} method were invoked. * *

If none of the previous conditions hold then this thread"s interrupt * status will be set.

可以看到如果線程處于正?;顒訝顟B(tài),那么會將該線程的中斷標(biāo)志設(shè)置為true,而無法中斷當(dāng)前的線程。所以,shutdownNow并不代表線程池就一定立即就能退出,它也可能必須要等待所有正在執(zhí)行的任務(wù)都執(zhí)行完成了才能退出。

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/77876.html

相關(guān)文章

  • Java SDK 并發(fā)包全面總結(jié)

    摘要:一和并發(fā)包中的和主要解決的是線程的互斥和同步問題,這兩者的配合使用,相當(dāng)于的使用。寫鎖與讀鎖之間互斥,一個線程在寫時,不允許讀操作。的注意事項不支持重入,即不可反復(fù)獲取同一把鎖。沒有返回值,也就是說無法獲取執(zhí)行結(jié)果。 一、Lock 和 Condition Java 并發(fā)包中的 Lock 和 Condition 主要解決的是線程的互斥和同步問題,這兩者的配合使用,相當(dāng)于 synchron...

    luckyyulin 評論0 收藏0
  • Java多線程(3):取消正在運(yùn)行的任務(wù)

    摘要:比如上一篇文章提到的線程池的方法,它可以在線程池中運(yùn)行一組任務(wù),當(dāng)其中任何一個任務(wù)完成時,方法便會停止阻塞并返回,同時也會取消其他任務(wù)。 當(dāng)一個任務(wù)正在運(yùn)行的過程中,而我們卻發(fā)現(xiàn)這個任務(wù)已經(jīng)沒有必要繼續(xù)運(yùn)行了,那么我們便產(chǎn)生了取消任務(wù)的需要。比如 上一篇文章 提到的線程池的 invokeAny 方法,它可以在線程池中運(yùn)行一組任務(wù),當(dāng)其中任何一個任務(wù)完成時,invokeAny 方法便會停...

    terro 評論0 收藏0
  • Java線程池

    摘要:中的線程池是運(yùn)用場景最多的并發(fā)框架。才是真正的線程池。存放任務(wù)的隊列存放需要被線程池執(zhí)行的線程隊列。所以線程池的所有任務(wù)完成后,它最終會收縮到的大小。飽和策略一般情況下,線程池采用的是,表示無法處理新任務(wù)時拋出異常。 Java線程池 1. 簡介 系統(tǒng)啟動一個新線程的成本是比較高的,因為它涉及與操作系統(tǒng)的交互,這個時候使用線程池可以提升性能,尤其是需要創(chuàng)建大量聲明周期很短暫的線程時。Ja...

    jerry 評論0 收藏0
  • 深入剖析ThreadPool的運(yùn)行原理

    摘要:而且,線程池中的線程并沒有睡眠,而是進(jìn)入了自旋狀態(tài)。普通的線程被中斷會導(dǎo)致線程繼續(xù)執(zhí)行,從而方法運(yùn)行完畢,線程退出。線程死亡超過時間,任務(wù)對列沒有數(shù)據(jù)而返回。線程死亡保證了線程池至少留下個線程。 線程在執(zhí)行任務(wù)時,正常的情況是這樣的: Thread t=new Thread(new Runnable() { @Override ...

    Pines_Cheng 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<