首页 > Java > java教程 > 正文

同步器的代码示例

聖光之護
发布: 2025-01-09 14:57:52
原创
1123人浏览过

同步器的代码示例

本文提供四个Java并发同步器的代码示例及使用方法,帮助您理解Java多线程编程中的同步机制

1. CountDownLatch:一次性屏障,协调线程

CountDownLatch允许一个或多个线程等待,直到其他线程完成一组操作。

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        int workerCount = 3;
        CountDownLatch latch = new CountDownLatch(workerCount);

        for (int i = 0; i < workerCount; i++) {
            new Thread(() -> {
                try {
                    // 模拟工作
                    Thread.sleep(1000);
                    System.out.println("Worker " + Thread.currentThread().getName() + " finished.");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown(); // 完成任务后计数器减一
                }
            }).start();
        }

        System.out.println("Main thread waiting for workers to finish...");
        latch.await(); // 主线程等待所有计数器变为0
        System.out.println("All workers finished. Main thread proceeding.");
    }
}
登录后复制

2. Semaphore:控制对共享资源的访问

Semaphore管理一组许可证,控制对有限资源的访问。

import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    public static void main(String[] args) {
        int permits = 2; // 可用许可证数量
        Semaphore semaphore = new Semaphore(permits);

        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire(); // 获取许可证
                    System.out.println("Thread " + Thread.currentThread().getName() + " acquired permit.");
                    // 使用共享资源
                    Thread.sleep(1000);
                    System.out.println("Thread " + Thread.currentThread().getName() + " releasing permit.");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release(); // 释放许可证
                }
            }).start();
        }
    }
}
登录后复制

3. CyclicBarrier:可重用的屏障点同步

CyclicBarrier在公共点(屏障)同步多个线程,所有线程到达屏障点后可重复使用。

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample {
    public static void main(String[] args) {
        int threadCount = 3;
        CyclicBarrier barrier = new CyclicBarrier(threadCount, () -> {
            System.out.println("All threads have reached the barrier. Proceeding...");
        });

        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                try {
                    // 模拟工作
                    Thread.sleep(1000);
                    System.out.println("Thread " + Thread.currentThread().getName() + " reached the barrier.");
                    barrier.await(); // 等待其他线程到达屏障
                    System.out.println("Thread " + Thread.currentThread().getName() + " passed the barrier.");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
登录后复制

4. Phaser:高级动态线程同步

Phaser类似于CyclicBarrier,但支持动态加入和离开线程。

import java.util.concurrent.Phaser;

public class PhaserExample {
    public static void main(String[] args) {
        Phaser phaser = new Phaser(1); // 注册“主方”

        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                System.out.println("Thread " + Thread.currentThread().getName() + " registered.");
                phaser.register(); // 注册线程
                try {
                    Thread.sleep(1000);
                    System.out.println("Thread " + Thread.currentThread().getName() + " arrived at phase " + phaser.getPhase());
                    phaser.arriveAndAwaitAdvance(); // 到达并等待其他线程
                    System.out.println("Thread " + Thread.currentThread().getName() + " passed phase " + phaser.getPhase());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    phaser.arriveAndDeregister(); // 完成并注销
                }
            }).start();
        }
        phaser.arriveAndAwaitAdvance(); // 主线程等待所有线程完成第一阶段
        System.out.println("All threads finished.");
    }
}
登录后复制

这些示例演示了每个同步器的基本用法。您可以修改线程数量和等待时间来观察同步行为的变化。 记住处理潜在的InterruptedException。

以上就是同步器的代码示例的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号