温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java并发之同步辅助类CountDownLatch的示例分析

发布时间:2021-12-16 17:34:14 来源:亿速云 阅读:151 作者:小新 栏目:大数据

这篇文章将为大家详细讲解有关java并发之同步辅助类CountDownLatch的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

CountDownLatch

含义:

CountDownLatch可以理解为一个计数器在初始化时设置初始值,当一个线程需要等待某些操作先完成时,需要调用await()方法。这个方法让线程进入休眠状态直到等待的所有线程都执行完成。每调用一次countDown()方法内部计数器减1,直到计数器为0时唤醒。这个可以理解为特殊的CyclicBarrier。线程同步点比较特殊,为内部计数器值为0时开始。

方法:

核心方法两个:countDown()和await()

countDown():使CountDownLatch维护的内部计数器减1,每个被等待的线程完成的时候调用

await():线程在执行到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();// 调用countDown()方法,使内部计数器减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计数器为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()方法,在内部计数器为0之前线程处于等待状态

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

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

Thread t = new Thread(p);

t.start();

}

}

}

关于“java并发之同步辅助类CountDownLatch的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI