博客
关于我
狂神JUC——CountDownLatch,CyclicBarrier,Semaphore
阅读量:511 次
发布时间:2019-03-07

本文共 2385 字,大约阅读时间需要 7 分钟。

CountDownLatch、CyclicBarrier与Semaphore:A Java多线程同步技术分析

在Java多线程编程中,CountDownLatch、CyclicBarrier以及Semaphore是三大核心的同步控制工具,它们各自在不同场景下发挥着重要作用。本文将从理论与实践角度,分析这三者各自的特点及其应用场景,并通过实际代码示例展示它们的使用方法。

CountDownLatch

CountDownLatch 是一个可重入同步机制,允许多个线程在不同的时间点等待基准事件完成。一旦基准事件发生,所有等待的线程都会立即被唤醒,并继续执行后续任务。

以下是一个典型的用法示例:

public static void main(String[] args) throws InterruptedException {    CountDownLatch countDownLatch = new CountDownLatch(5);    for (int i = 1; i <= 6; i++) {        new Thread(() -> {            System.out.println(Thread.currentThread().getName() + "go out");            try {                countDownLatch.await();            } catch (InterruptedException e) {                e.printStackTrace();            }        }, String.valueOf(i)).start();    }    countDownLatch.await();    System.out.println("Close Door");}

运行结果显示,所有线程均正确执行,门禁系统按预期关闭。


CyclicBarrier

CyclicBarrier 是一种允许多个线程组成的循环关卡,支持线程在一系列阶段间幕间等待。有时称为" Barney doors",其原理是所有线程必须完成指定阶段后才能继续下一阶段任务。

一个典型的应用示例如下:

public static void main(String[] args) {    CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {        System.out.println("Summon Dragon");    });    for (int i = 1; i <= 7; i++) {        final int temp = i;        new Thread(() -> {            System.out.println(Thread.currentThread().getName() + "Collect第" + temp + "个龙珠");            try {                cyclicBarrier.await();            } catch (InterruptedException e) {                e.printStackTrace();            } catch (BrokenBarrierException e) {                e.printStackTrace();            }        }, String.valueOf(i)).start();    }}

运行结果表明,所有线程正确地收集了所有的龙珠。


Semaphore

Semaphore 是一个信号量机制,用于限制并发访问共享资源。它通过颗粒式许可证来管理共享资源的访问数量,确保线程不会无限制地抢占资源。

一个典型的代码案例:

public static void main(String[] args) {    Semaphore semaphore = new Semaphore(3);    for (int i = 1; i <= 6; i++) {        new Thread(() -> {            try {                semaphore.acquire();                System.out.println(Thread.currentThread().getName() + "抢到车位");                TimeUnit.SECONDS.sleep(2);                System.out.println(Thread.currentThread().getName() + "离开车位");            } catch (InterruptedException e) {                e.printStackTrace();            } finally {                semaphore.release();            }        }, String.valueOf(i)).start();    }}

运行结果显示,前三线程成功抢到车位,后续线程会依次等待进入。


这些同步机制在多线程开发中的应用场景各有不同。选择合适的工具依赖于具体任务需求,了解它们的工作原理和使用方法是成功应用的关键。

转载地址:http://jyhjz.baihongyu.com/

你可能感兴趣的文章
NOTE:rfc5766-turn-server
查看>>
Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
查看>>
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad++最详情汇总
查看>>
notepad++正则表达式替换字符串详解
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
nova基于ubs机制扩展scheduler-filter
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>