java并發(fā)之同步輔助類CountDownLatch的示例分析

這篇文章將為大家詳細講解有關(guān)java并發(fā)之同步輔助類CountDownLatch的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

專注于為中小企業(yè)提供成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計服務(wù),電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業(yè)臨湘免費做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了1000多家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實現(xiàn)規(guī)模擴充和轉(zhuǎn)變。

CountDownLatch

含義:

CountDownLatch可以理解為一個計數(shù)器在初始化時設(shè)置初始值,當(dāng)一個線程需要等待某些操作先完成時,需要調(diào)用await()方法。這個方法讓線程進入休眠狀態(tài)直到等待的所有線程都執(zhí)行完成。每調(diào)用一次countDown()方法內(nèi)部計數(shù)器減1,直到計數(shù)器為0時喚醒。這個可以理解為特殊的CyclicBarrier。線程同步點比較特殊,為內(nèi)部計數(shù)器值為0時開始。

方法:

核心方法兩個:countDown()和await()

countDown():使CountDownLatch維護的內(nèi)部計數(shù)器減1,每個被等待的線程完成的時候調(diào)用

await():線程在執(zhí)行到CountDownLatch的時候會將此線程置于休眠

例子

開會的例子:會議室里等與會人員到齊了會議才能開始。

import java.util.concurrent.CountDownLatch;

public class VideoConference implements Runnable {

private final CountDownLatch controller;

public VideoConference(int number) {

controller = new CountDownLatch(number);

}

public void arrive(String name) {

System.out.printf("%s has arrived.\n", name);

controller.countDown();// 調(diào)用countDown()方法,使內(nèi)部計數(shù)器減1

System.out.printf("VideoConference: Waiting for %d participants.\n", controller.getCount());

}

@Override

public void run() {

System.out.printf("VideoConference: Initialization: %d participants.\n", controller.getCount());

try {

controller.await();// 等待,直到CoutDownLatch計數(shù)器為0

System.out.printf("VideoConference: All the participants have come\n");

System.out.printf("VideoConference: Let's start...\n");

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

參加會議人員類

import java.util.concurrent.Semaphore;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class PrintQueue {

//信號量

    private Semaphore semaphore;

    //是否空閑打印機

    private boolean freePrinters[];

    private Lock lockPrinters;

    public PrintQueue(){

     //初始化三個信號

        semaphore=new Semaphore(3);

        //三臺空閑打印機

        freePrinters=new boolean[3];

        for (int i=0; i<3; i++){

            freePrinters[i]=true;

        }

        lockPrinters=new ReentrantLock();

    }

    public void printJob (Object document){

        try {

         //獲取信號量

            semaphore.acquire();

            int assignedPrinter=getPrinter();

            Long duration=(long)(Math.random()*10);

            System.out.printf("%s: PrintQueue: Printing a Job in Printer %d during %d seconds\n",Thread.currentThread().getName(),assignedPrinter,duration);

            TimeUnit.SECONDS.sleep(duration);

            freePrinters[assignedPrinter]=true;

        } catch (InterruptedException e) {

            e.printStackTrace();

        } finally {

            // Free the semaphore

            semaphore.release();            

        }

    }

    private int getPrinter() {

        int ret=-1;

        try {

            lockPrinters.lock();

            for (int i=0; i<freePrinters.length; i++) {

                if (freePrinters[i]){

                    ret=i;

                    freePrinters[i]=false;

                    break;

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            lockPrinters.unlock();

        }

        return ret;

    }

}

測試類:

public class CountDownLatchMain {

public static void main(String[] args) {

VideoConference conference = new VideoConference(10);

Thread threadConference = new Thread(conference);

threadConference.start();// 開啟await()方法,在內(nèi)部計數(shù)器為0之前線程處于等待狀態(tài)

for (int i = 0; i < 10; i++) {

Participant p = new Participant(conference, "Participant " + i);

Thread t = new Thread(p);

t.start();

}

}

}

關(guān)于“java并發(fā)之同步輔助類CountDownLatch的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

當(dāng)前文章:java并發(fā)之同步輔助類CountDownLatch的示例分析
標(biāo)題URL:http://bm7419.com/article44/pciiee.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、App設(shè)計品牌網(wǎng)站制作、標(biāo)簽優(yōu)化、服務(wù)器托管、商城網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運營