博客
关于我
狂神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/

你可能感兴趣的文章
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>