最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java多線程之同步工具類CountDownLatch

 更新時(shí)間:2022年06月29日 10:55:35   作者:冬日毛毛雨  
這篇文章主要介紹了Java多線程之同步工具類CountDownLatch,CountDownLatch是一個(gè)同步工具類,它允許一個(gè)或多個(gè)線程一直等待,直到其他線程執(zhí)行完后再執(zhí)行。例如,應(yīng)用程序的主線程希望在負(fù)責(zé)啟動(dòng)框架服務(wù)的線程已經(jīng)啟動(dòng)所有框架服務(wù)之后執(zhí)行,下面一起來學(xué)習(xí)學(xué)習(xí)內(nèi)容吧

前言:

CountDownLatch是一個(gè)同步工具類,它允許一個(gè)或多個(gè)線程一直等待,直到其他線程執(zhí)行完后再執(zhí)行。例如,應(yīng)用程序的主線程希望在負(fù)責(zé)啟動(dòng)框架服務(wù)的線程已經(jīng)啟動(dòng)所有框架服務(wù)之后執(zhí)行。

1 CountDownLatch主要方法

void await():如果當(dāng)前count大于0,當(dāng)前線程將會(huì)wait,直到count等于0或者中斷。 PS:當(dāng)count等于0的時(shí)候,再去調(diào)用await() ,
線程將不會(huì)阻塞,而是立即運(yùn)行。后面可以通過源碼分析得到。
boolean await(long timeout, TimeUnit unit):使當(dāng)前線程在鎖存器倒計(jì)數(shù)至零之前一直等待,除非線程被中斷或超出了指定的等待時(shí)間。
void countDown(): 遞減鎖存器的計(jì)數(shù),如果計(jì)數(shù)到達(dá)零,則釋放所有等待的線程。
long getCount() :獲得計(jì)數(shù)的數(shù)量

2 CountDownLatch使用例子

public class CountDownLatchTest {
    private static final  int N = 4;
    public static void main(String[] args) {

        final CountDownLatch latch = new CountDownLatch(4);

        for(int i=0;i<N;i++)
        {
            new Thread(){
                public void run() {
                    try {
                        System.out.println("子線程"+Thread.currentThread().getName()+"正在執(zhí)行");
                        Thread.sleep(3000);
                        System.out.println("子線程"+Thread.currentThread().getName()+"執(zhí)行完畢");
                        latch.countDown();
                        System.out.println("剩余計(jì)數(shù)"+latch.getCount());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                };
            }.start();
        }


        try {
            System.out.println("等待"+N+"個(gè)子線程執(zhí)行完畢...");
            latch.await();
            System.out.println(N+"個(gè)子線程已經(jīng)執(zhí)行完畢");
            System.out.println("繼續(xù)執(zhí)行主線程");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

子線程Thread-1正在執(zhí)行
子線程Thread-3正在執(zhí)行
子線程Thread-2正在執(zhí)行
等待4個(gè)子線程執(zhí)行完畢...
子線程Thread-0正在執(zhí)行
子線程Thread-3執(zhí)行完畢
子線程Thread-2執(zhí)行完畢
剩余計(jì)數(shù)2
子線程Thread-1執(zhí)行完畢
剩余計(jì)數(shù)1
子線程Thread-0執(zhí)行完畢
剩余計(jì)數(shù)3
剩余計(jì)數(shù)0
4個(gè)子線程已經(jīng)執(zhí)行完畢
繼續(xù)執(zhí)行主線程

3 CountDownLatch源碼分析

CountDownLatch是通過計(jì)數(shù)器的方式來實(shí)現(xiàn),計(jì)數(shù)器的初始值為線程的數(shù)量。每當(dāng)一個(gè)線程完成了自己的任務(wù)之后,就會(huì)對計(jì)數(shù)器減1,當(dāng)計(jì)數(shù)器的值為0時(shí),表示所有線程完成了任務(wù),此時(shí)等待在閉鎖上的線程才繼續(xù)執(zhí)行,從而達(dá)到等待其他線程完成任務(wù)之后才繼續(xù)執(zhí)行的目的。

構(gòu)造函數(shù)

public CountDownLatch(int count) {
    if (count < 0) throw new IllegalArgumentException("count < 0");
    this.sync = new Sync(count);
}

通過傳入一個(gè)數(shù)值來創(chuàng)建一個(gè)CountDownLatch,數(shù)值表示線程可以從等待狀態(tài)恢復(fù),countDown方法必須被調(diào)用的次數(shù)

countDown方法

public void countDown() {
        sync.releaseShared(1);
    }

線程調(diào)用此方法對count進(jìn)行減1。當(dāng)count本來就為0,此方法不做任何操作,當(dāng)count比0大,調(diào)用此方法進(jìn)行減1,當(dāng)new count為0,釋放所有等待當(dāng)線程。

countDown方法的內(nèi)部實(shí)現(xiàn)

   /**
     * Decrements the count of the latch, releasing all waiting threads if
     * the count reaches zero.
     *
     * <p>If the current count is greater than zero then it is decremented.
     * If the new count is zero then all waiting threads are re-enabled for
     * thread scheduling purposes.
     *
     * <p>If the current count equals zero then nothing happens.
     */
    public void countDown() {
        sync.releaseShared(1);
    }


    public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();//釋放所有正在等待的線程節(jié)點(diǎn)
            return true;
        }
        return false;
    }

        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    private void doReleaseShared() {
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

await方法

(1)不帶參數(shù)

public void await() throws InterruptedException {
    sync.acquireSharedInterruptibly(1);
}

調(diào)用此方法時(shí),當(dāng)count為0,直接返回true,當(dāng)count比0大,線程會(huì)一直等待,直到count的值變?yōu)?,或者線程被中斷(interepted,此時(shí)會(huì)拋出中斷異常)。

(2)帶參數(shù)

public boolean await(long timeout, TimeUnit unit)
    throws InterruptedException {
    return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}

調(diào)用此方法時(shí),當(dāng)count為0,直接返回true,當(dāng)count比0大,線程會(huì)等待一段時(shí)間,等待時(shí)間內(nèi)如果count的值變?yōu)?,返回true;當(dāng)超出等待時(shí)間,返回false;或者等待時(shí)間內(nèi)線程被中斷,此時(shí)會(huì)拋出中斷異常。

await()方法的內(nèi)部實(shí)現(xiàn)

public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }


具體如下:

  • 1、檢測中斷標(biāo)志位
  • 2、調(diào)用tryAcquireShared方法來檢查AQS標(biāo)志位state是否等于0,如果state等于0,則說明不需要等待,立即返回,否則進(jìn)行3
  • 3、調(diào)用doAcquireSharedInterruptibly方法進(jìn)入AQS同步隊(duì)列進(jìn)行等待,并不斷的自旋檢測是否需要喚醒
    public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();

        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
    /*
        函數(shù)功能:根據(jù)AQS的狀態(tài)位state來返回值,
        如果為state=0,返回 1
        如果state=1,則返回-1
    */
    protected int tryAcquireShared(int acquires) {
        return (getState() == 0) ? 1 : -1;
    }

    /**
     * Acquires in shared interruptible mode.
     * @param arg the acquire argument
     */
    private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {//如果大于零,則說明需要喚醒
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

4 CountDownLatch和CyclicBarrier區(qū)別

CountDownLatchCyclicBarrier都能夠?qū)崿F(xiàn)線程之間的等待,只不過它們側(cè)重點(diǎn)不同:

  • CountDownLatch一般用于某個(gè)線程A等待若干個(gè)其他線程執(zhí)行完任務(wù)之后,它才執(zhí)行;
  • CyclicBarrier一般用于一組線程互相等待至某個(gè)狀態(tài),然后這一組線程再同時(shí)執(zhí)行;

CountDownLatch是不能夠重用的,而CyclicBarrier是可以重用的。

到此這篇關(guān)于Java多線程之同步工具類CountDownLatch的文章就介紹到這了,更多相關(guān)Java多線程 CountDownLatch內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • idea中MavenWeb項(xiàng)目不能創(chuàng)建Servlet的解決方案

    idea中MavenWeb項(xiàng)目不能創(chuàng)建Servlet的解決方案

    這篇文章主要介紹了idea中MavenWeb項(xiàng)目不能創(chuàng)建Servlet的解決方案,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-02-02
  • SpringBoot 創(chuàng)建對象常見的幾種方式小結(jié)

    SpringBoot 創(chuàng)建對象常見的幾種方式小結(jié)

    Spring Boot中創(chuàng)建對象的幾種常見方式包括使用@Component、@Service、@Repository或@Controller注解,本文就來詳細(xì)的介紹一下,感興趣的可以了解一下
    2024-11-11
  • ConcurrentModificationException日志關(guān)鍵字報(bào)警思考分析

    ConcurrentModificationException日志關(guān)鍵字報(bào)警思考分析

    本文將記錄和分析日志中的ConcurrentModificationException關(guān)鍵字報(bào)警,還有一些我的思考,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2023-12-12
  • Java讀取Properties文件幾種方法總結(jié)

    Java讀取Properties文件幾種方法總結(jié)

    這篇文章主要介紹了 Java讀取Properties文件幾種方法總結(jié)的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • Springcloud Config支持本地配置文件的方法示例

    Springcloud Config支持本地配置文件的方法示例

    這篇文章主要介紹了Springcloud Config支持本地配置文件的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • spring boot配置ssl實(shí)現(xiàn)HTTPS的方法

    spring boot配置ssl實(shí)現(xiàn)HTTPS的方法

    這篇文章主要介紹了spring boot配置ssl實(shí)現(xiàn)HTTPS的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-03-03
  • Spring中常見的7種BeanDefinition詳解

    Spring中常見的7種BeanDefinition詳解

    在?Spring?容器中,我們廣泛使用的是一個(gè)一個(gè)的?Bean,BeanDefinition?從名字上就可以看出是關(guān)于?Bean?的定義,下面就跟隨小編一起深入了解一下常見的7中BeanDefinition吧
    2023-09-09
  • IDEA+Maven搭建JavaWeb項(xiàng)目的方法步驟

    IDEA+Maven搭建JavaWeb項(xiàng)目的方法步驟

    本文主要介紹了IDEA+Maven搭建JavaWeb項(xiàng)目的方法步驟,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • 基于Java反射技術(shù)實(shí)現(xiàn)簡單IOC容器

    基于Java反射技術(shù)實(shí)現(xiàn)簡單IOC容器

    這篇文章主要介紹了基于Java反射技術(shù)實(shí)現(xiàn)簡單IOC容器,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • Java如何重寫object類的equals方法詳解

    Java如何重寫object類的equals方法詳解

    這篇文章主要給大家介紹了關(guān)于Java如何重寫object類的equals方法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12

最新評論

江门市| 响水县| 海兴县| 尖扎县| 湛江市| 聂拉木县| 林芝县| 定西市| 梅州市| 郁南县| 清远市| 丽水市| 福清市| 扎兰屯市| 介休市| 龙山县| 冀州市| 西乡县| 竹山县| 宁安市| 凤山市| 若尔盖县| 梁山县| 怀集县| 衡阳县| 关岭| 哈尔滨市| 云阳县| 渭源县| 谢通门县| 普定县| 久治县| 都江堰市| 抚宁县| 孙吴县| 焉耆| 白水县| 彩票| 钟祥市| 台安县| 正宁县|