JAVA并发编程: CountDownLatch,CyclicBarrier 和 Semaphore

JDK1.5 之后,引入了 CountDownLatch,CyclicBarrier 和 Semaphore

CyclicBarrier

打游戏的时候,必须等所有玩家都加载完毕,我们才能开始游戏,这就用到了CyclicBarrier

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

翻译:让一些列线程相互等待直到达到公共障碍点,这被称为cylic是因为这能被重新使用。
其构造函数如下:parties指的是线程个数,barrierAction指的是当这些线程都打到barrier后执行的内容。

public CyclicBarrier(int parties, Runnable barrierAction) {
}
 
public CyclicBarrier(int parties) {
}

CyclicBarrier中最重要的是await()方法,当线程准备完毕后等待其他线程

public int await() throws InterruptedException, BrokenBarrierException { };

Run类实现Runnable,重写run方法:

public class Run implements Runnable {

    private CyclicBarrier barrier;
    private String name;

    public Run(CyclicBarrier barrier, String name) {
        super();
        this.barrier = barrier;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(600 * (new Random()).nextInt(8));
            System.out.println("用户:" + name +" 准备完毕 !");
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

下列函数中barrier构造函数第二个参数就是barrierAction,主函数如下:

public static void main(String[] args) {

        CyclicBarrier barrier = new CyclicBarrier(4, new Runnable() {
            @Override
            public void run() {
                System.out.println("游戏开始");
            }
        });

        for(int i = 0; i < 4; ++i) {
            new Thread(new Run(barrier, String.valueOf(i))).start();
        }
    }

打印结果:

用户:0 准备完毕 !
用户:3 准备完毕 !
用户:2 准备完毕 !
用户:1 准备完毕 !
游戏开始

CountDownLatch

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

翻译:帮助线程一直等待直到其他线程完成一些列操作

CountDownLatch 的 await方法,让计数器为0才能执行接下去步骤。

这里 -> 使用的是 JAVA lambda表达式,就是匿名函数。

public static void main(String[] args) {

        final CountDownLatch latch = new CountDownLatch(2);

        new Thread(() -> {
            System.out.println("子线程1 开始执行");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程1 执行完毕");
	        latch.countDown();
        }).start();
        
        new Thread(() -> {
            System.out.println("子线程2 开始执行");
            try{
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子程序2 执行完毕");
            latch.countDown();
        }).start();

        try{
            latch.await();
            System.out.println("所有线程执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

执行结果打印如下:

子线程1 开始执行
子线程2 开始执行
子线程1 执行完毕
子程序2 执行完毕
所有线程执行完毕

Semaphore

A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each ‘acquire()’ blocks if necessary until a permit is available, and then takes it. Each ‘release()’ adds a permit,
potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

翻译:一个计数的semaphore,概念上来说,semaphore维护一系列许可。每个acquire()方法在必要的时候阻塞进程直到获得许可。每个release()方法释放一个许可,潜在地释放一个阻塞的获取方(acquirer)。然而没有用到实际的对象,semaphore只是记录可用许可的量,并据此采取行动。

构造函数:

public Semaphore(int permits) {          //参数permits表示许可数目,即同时可以允许多少线程进行访问
    sync = new NonfairSync(permits);
}

public Semaphore(int permits, boolean fair) {    //这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可
    sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
}

本文使用对象以电脑为例子,一共两台电脑,6个玩家要使用电脑
Run类实现Runable,重写run方法,代码如下:

public class Run implements Runnable {

    private Semaphore semaphore;
    private String name;

    public Run(Semaphore semaphore, String name) {
        super();
        this.semaphore = semaphore;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(600 * (new Random()).nextInt(8));
            semaphore.acquire();
            System.out.println("用户:" + name +" 使用了一台电脑");
            Thread.sleep(4000);
            semaphore.release();
            System.out.println("用户:" + name +" 释放了一台电脑");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

主函数代码如下:

public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(2);

        for(int i = 1; i <= 6; ++i) {
            new Thread(new Run(semaphore, String.valueOf(i))).start();
        }
    }

结果打印如下:

用户:6 使用了一台电脑
用户:2 使用了一台电脑
用户:2 释放了一台电脑
用户:3 使用了一台电脑
用户:6 释放了一台电脑
用户:5 使用了一台电脑
用户:3 释放了一台电脑
用户:4 使用了一台电脑
用户:5 释放了一台电脑
用户:1 使用了一台电脑
用户:1 释放了一台电脑
用户:4 释放了一台电脑

总结

CountDownLatch和CyclicBarrier都能完成线程相互等待,不过有以下区别:
CountDownLatch一般用于某个线程A等待若干个其他线程执行完任务之后,它才执行;
而CyclicBarrier一般用于一组线程互相等待至某个状态,然后这一组线程再同时执行;

另外,CountDownLatch是不能够重复使用的,而CyclicBarrier是可以重复使用的。
Semaphore其实和锁有点类似,它一般用于控制对某组资源的访问权限。

Reference / 参考:

https://www.fangzhipeng.com/javainterview/2019/03/21/latch-barrier-semaphore.html

https://blog.csdn.net/qq_38078822/article/details/80836539

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值