zoukankan      html  css  js  c++  java
  • CountDownLatch CyclicBarrier Semaphore 比较

    document

    • CountDownLatch

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

    • CyclicBarrier

    A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

    • 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


    释义

    • CountDownLatch : 一个线程(或者多个), 等待另外N个线程完成某个事情之后才能执行。
    • CyclicBarrier : N个线程相互等待,任何一个线程完成之前,所有的线程都必须等待。
    • Semaphore:可以控制某个资源可被同时访问的个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。

    使用场景举例

    • CountDownLatch

    体育课时老师拿着秒表测试同学的800米成绩,那需求就是很简单了,老师在起跑处组织大家一起跑的瞬间按下秒表计时开始,然后再终点处等待最后一个学生通过终点后开始汇集学生成绩。

    • CyclicBarrier

    有四个游戏玩家玩游戏,游戏有三个关卡,每个关卡必须要所有玩家都到达后才能允许通关。
    其实这个场景里的玩家中如果有玩家A先到了关卡1,他必须等待其他所有玩家都到达关卡1时才能通过。
    也就是说线程之间需要互相等待,这和CountDownLatch的应用场景有区别,
    CountDownLatch里的线程是到了运行的目标后继续干自己的其他事情,而这里的线程需要等待其他线程后才能继续完成下面的工作。

    • Semaphore

    一个资源池只能同时五个人使用,那么十个人来轮询使用的情况就是每个人都先申请资源,使用完归还于下一个人使用。

    Phaser

    Java 7的并发包中推出了Phaser,其功能跟CyclicBarrier和CountDownLatch有些重叠,但是提供了更灵活的用法,例如支持动态调整注册任务的数量等

    转自:http://www.liubey.org/countdownlatch_vs_cyclicbarrier/

  • 相关阅读:
    postgresql 高可用 etcd + patroni 之八 haproxy + keepalived
    postgresql 高可用 etcd + patroni 之七 haproxy
    postgresql 索引之 gin
    postgresql 索引之 btree
    postgresql 物理备份 barman 之 rsync/ssh backup
    postgresql 物理备份 barman 之 streaming backup
    postgresql 物理备份 barman 之 安装
    postgresql 的 .pgpass密码文件的使用
    postgresql 的 pg_hba.conf 的行记录顺序
    ubuntu 16.04 进入单用户模式
  • 原文地址:https://www.cnblogs.com/olmlo/p/4806922.html
Copyright © 2011-2022 走看看