亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

ThreadPool實(shí)現(xiàn)原理

spacewander / 1815人閱讀

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

本文主要分析java.util.concurrent.ThreadPoolExecutor的實(shí)現(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ù)(一開(kāi)始會(huì)小于這個(gè)數(shù))

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

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

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

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

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

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

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

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)建線程是通過(guò)addWorker創(chuàng)建內(nèi)部Worker類,其中調(diào)用getThreadFactory().newThread(this)來(lái)創(chuàng)建執(zhí)行自己的線程,之后在addWorker中start該線程,執(zhí)行Worker run方法中的runWorker會(huì)不斷的從任務(wù)隊(duì)列中獲取任務(wù)或阻塞,并且每次執(zhí)行任務(wù)前會(huì)執(zhí)行beforeExecute,之后會(huì)afterExecute,可以通過(guò)重寫beforeExecute方法來(lái)給執(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終止線程的方法是通過(guò)調(diào)用Thread.interrupt()方法來(lái)實(shí)現(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.

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

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

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/77876.html

相關(guān)文章

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

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

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

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

    terro 評(píng)論0 收藏0
  • Java線程池

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

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

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

    Pines_Cheng 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<