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

資訊專欄INFORMATION COLUMN

線程池的狀態(tài)及KeepAliveTime參數(shù)

Yang_River / 1914人閱讀

摘要:在程序某些必要的情況下,可以通過線程池的,,,來對線程做一些狀態(tài)判定。默認(rèn)的工廠,只有,為秒,出現(xiàn)情況下,而且線程數(shù)超過了核心線程數(shù),會銷毀銷毀線程。線程池最小是,最大是,除非設(shè)置了和超時(shí)時(shí)間,這種情況線程數(shù)可能減少到,最大可能是。

五個(gè)狀態(tài)
    // runState is stored in the high-order bits
    private static final int RUNNING    = -1 << COUNT_BITS;
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
    private static final int STOP       =  1 << COUNT_BITS;
    private static final int TIDYING    =  2 << COUNT_BITS;
    private static final int TERMINATED =  3 << COUNT_BITS;
循環(huán)getTask方法
/**
     * Performs blocking or timed wait for a task, depending on
     * current configuration settings, or returns null if this worker
     * must exit because of any of:
     * 1. There are more than maximumPoolSize workers (due to
     *    a call to setMaximumPoolSize).
     * 2. The pool is stopped.
     * 3. The pool is shutdown and the queue is empty.
     * 4. This worker timed out waiting for a task, and timed-out
     *    workers are subject to termination (that is,
     *    {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
     *    both before and after the timed wait.
     *
     * @return task, or null if the worker must exit, in which case
     *         workerCount is decremented
     */
    private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);
            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }
            boolean timed;      // Are workers subject to culling?
            for (;;) {
                int wc = workerCountOf(c);
                timed = allowCoreThreadTimeOut || wc > corePoolSize;
                //默認(rèn)allowCoreThreadTimeOut為false,除非程序指定
                //(1)當(dāng)沒有超過核心線程時(shí),默認(rèn)allowCoreThreadTimeOut為false時(shí)
                //timed值為false,始終break掉,不會銷毀線程
                //(2)當(dāng)超過核心線程數(shù),默認(rèn)allowCoreThreadTimeOut為false時(shí)
                //timed值為true,如果超過最大值,則銷毀;如果timeout過,則銷毀
                // 如果allowCoreThreadTimeOut為true,則timed始終為true
                if (wc <= maximumPoolSize && ! (timedOut && timed))
                    break;
                if (compareAndDecrementWorkerCount(c))
                    return null;
                c = ctl.get();  // Re-read ctl
                if (runStateOf(c) != rs)
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }
線程池狀態(tài)大于SHUTDOWN值的兩種情況 1、調(diào)用shutdown方法

當(dāng)線程池調(diào)用了shutdown方法,線程池的狀態(tài)會首先被設(shè)置為SHUTDOWN,然后遍歷線程池中所有線程,調(diào)用一次interrupt方法,如果在休眠中的線程將會激活,激活后的線程以及調(diào)用shutdown方法本身的線程都會嘗試去調(diào)用tryTerminate方法,該方法將判定如果線程池中所有記錄的線程數(shù)為0,則將線程狀態(tài)改為TERMINATED,這個(gè)值為3,將大于SHUTDOWN狀態(tài)值。

2、調(diào)用shutdownNow方法

當(dāng)線程調(diào)用了shutdownNow方法后,首先將線程的狀態(tài)修改為STOP,這個(gè)狀態(tài)是大于SHUTDOWN值的,接下來它也會通過中斷激活線程,只是它來的更暴力一些,連加鎖和一些基本判斷都沒有,直接中斷;在調(diào)用tryTerminate之前會先清空阻塞隊(duì)列中所有的元素,這些元素被組裝為一個(gè)List列表作為shutdownNow方法的返回值。換句話說,沒有執(zhí)行的任務(wù)在shutdownNow執(zhí)行后的返回值中可以得到。在程序某些必要的情況下,可以通過線程池的isTerminating,isTerminated,isStopped,isShutdown來對線程做一些狀態(tài)判定。

KeepAliveTime參數(shù)
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS)

當(dāng)阻塞隊(duì)列中沒有任務(wù)時(shí),等待時(shí)間達(dá)到keepAliveTime毫秒值時(shí)就會被自動喚醒,而不會永遠(yuǎn)地沉睡下去。

keepAliveTime,如果是通過newCachedThreadPool的話,默認(rèn)是1分鐘超時(shí),如果遇到前面所提到的瞬間沖擊,那么線程池?cái)?shù)量將瞬間快速膨脹,而且這些瞬間膨脹的線程的生命周期最少在1分鐘以上。

如果設(shè)置了該參數(shù),那么當(dāng)timeout的時(shí)候,就return null,就會跳出循環(huán),回收線程。

if (wc <= maximumPoolSize && ! (timedOut && timed))
                    break;
                if (compareAndDecrementWorkerCount(c))
                    return null;

allowCoreThreadTimeout : 默認(rèn)情況下核心線程不會退出,可通過將該參數(shù)設(shè)置為true,讓核心線程也退出。

默認(rèn)的Executors工廠,只有newCachedThreadPool,timeout為60秒,出現(xiàn)timeout情況下,而且線程數(shù)超過了核心線程數(shù),會銷毀銷毀線程。保持在corePoolSize數(shù)(如果是cached的,corePoolSize為0)。

   /**
     * Timeout in nanoseconds for idle threads waiting for work.
     * Threads use this timeout when there are more than corePoolSize
     * present or if allowCoreThreadTimeOut. Otherwise they wait
     * forever for new work.
     */
    private volatile long keepAliveTime;
    /**
     * If false (default), core threads stay alive even when idle.
     * If true, core threads use keepAliveTime to time out waiting
     * for work.
     */
    private volatile boolean allowCoreThreadTimeOut;

線程池最小是corePoolSize,最大是maximumPoolSize,除非設(shè)置了allowCoreThreadTimeOut和超時(shí)時(shí)間,這種情況線程數(shù)可能減少到0,最大可能是Integer.MAX_VALUE。

Core pool size is the minimum number of workers to keep alive(and not allow to time out etc) unless allowCoreThreadTimeOut is set, in which case the minimum is zero.

/**
     * Creates a thread pool that creates new threads as needed, but
     * will reuse previously constructed threads when they are
     * available.  These pools will typically improve the performance
     * of programs that execute many short-lived asynchronous tasks.
     * Calls to execute will reuse previously constructed
     * threads if available. If no existing thread is available, a new
     * thread will be created and added to the pool. Threads that have
     * not been used for sixty seconds are terminated and removed from
     * the cache. Thus, a pool that remains idle for long enough will
     * not consume any resources. Note that pools with similar
     * properties but different details (for example, timeout parameters)
     * may be created using {@link ThreadPoolExecutor} constructors.
     *
     * @return the newly created thread pool
     */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue());
    }
    /**
     * Creates a thread pool that creates new threads as needed, but
     * will reuse previously constructed threads when they are
     * available, and uses the provided
     * ThreadFactory to create new threads when needed.
     * @param threadFactory the factory to use when creating new threads
     * @return the newly created thread pool
     * @throws NullPointerException if threadFactory is null
     */
    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue(),
                                      threadFactory);
    }
超時(shí)timeout設(shè)置為0的話,表示不等待
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        return pollFirst(timeout, unit);
    }

具體如下

public E pollFirst(long timeout, TimeUnit unit)
        throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            E x;
            while ( (x = unlinkFirst()) == null) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            return x;
        } finally {
            lock.unlock();
        }
    }

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

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

相關(guān)文章

  • Android 線程池的類型、區(qū)別以為何要用線程

    摘要:線程池根據(jù)當(dāng)前在系統(tǒng)中運(yùn)行的進(jìn)程來優(yōu)化線程片。線程池可以用來解決處理一個(gè)特定請求最大線程數(shù)量限制問題。線程池中允許的線程最大數(shù)量,當(dāng)活動線程達(dá)到這個(gè)數(shù)值后,后續(xù)的新任務(wù)會被阻塞。 每個(gè) Android 應(yīng)用進(jìn)程在創(chuàng)建時(shí),會同時(shí)創(chuàng)建一個(gè)線程,我們稱之為主線程,負(fù)責(zé)更新 UI 界面以及和處理用戶之間的交互,因此,在 Android 中,我們又稱之為 UI 線程。一個(gè)進(jìn)程中 UI 線程只有一...

    caiyongji 評論0 收藏0
  • java并發(fā)編程學(xué)習(xí)2--Future

    摘要:一個(gè)線程池包含很多準(zhǔn)備運(yùn)行的空閑線程,每當(dāng)執(zhí)行完畢后,線程不會死亡而是回到線程池準(zhǔn)備為下一個(gè)請求提供服務(wù)。另一個(gè)使用線程池的理由是減少并發(fā)線程數(shù)。創(chuàng)建大量線程會大大降低性能甚至拖垮虛擬機(jī)。 【Future的概念 interface Future ,表示異步計(jì)算的結(jié)果,F(xiàn)uture有個(gè)get方法而獲取結(jié)果只有在計(jì)算完成時(shí)獲取,否則會一直阻塞直到任務(wù)轉(zhuǎn)入完成狀態(tài),然后會返回結(jié)果或者拋出異常...

    weizx 評論0 收藏0
  • 后端ing

    摘要:當(dāng)活動線程核心線程非核心線程達(dá)到這個(gè)數(shù)值后,后續(xù)任務(wù)將會根據(jù)來進(jìn)行拒絕策略處理。線程池工作原則當(dāng)線程池中線程數(shù)量小于則創(chuàng)建線程,并處理請求。當(dāng)線程池中的數(shù)量等于最大線程數(shù)時(shí)默默丟棄不能執(zhí)行的新加任務(wù),不報(bào)任何異常。 spring-cache使用記錄 spring-cache的使用記錄,坑點(diǎn)記錄以及采用的解決方案 深入分析 java 線程池的實(shí)現(xiàn)原理 在這篇文章中,作者有條不紊的將 ja...

    roadtogeek 評論0 收藏0
  • 線程池源碼分析

    摘要:線程池的作用線程池能有效的處理多個(gè)線程的并發(fā)問題,避免大量的線程因?yàn)榛ハ鄰?qiáng)占系統(tǒng)資源導(dǎo)致阻塞現(xiàn)象,能夠有效的降低頻繁創(chuàng)建和銷毀線程對性能所帶來的開銷。固定的線程數(shù)由系統(tǒng)資源設(shè)置。線程池的排隊(duì)策略與有關(guān)。線程池的狀態(tài)值分別是。 線程池的作用 線程池能有效的處理多個(gè)線程的并發(fā)問題,避免大量的線程因?yàn)榛ハ鄰?qiáng)占系統(tǒng)資源導(dǎo)致阻塞現(xiàn)象,能夠有效的降低頻繁創(chuàng)建和銷毀線程對性能所帶來的開銷。 線程池的...

    enda 評論0 收藏0

發(fā)表評論

0條評論

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