• 高级同步机制:Phaser与CountDownLatch详解


    Java并发编程中,同步机制是确保多线程环境下数据一致性和程序正确性的关键。Java提供了多种同步工具,其中PhaserCountDownLatch是两个强大的工具,它们可以帮助我们更好地控制线程的执行顺序和同步。

    1. CountDownLatch

    CountDownLatch是一个非常实用的同步工具,它允许一个或多个线程等待其他线程完成操作。CountDownLatch通过一个给定的计数器来实现,当计数器减至0时,等待的线程将被释放。

    代码示例:
    1. import java.util.concurrent.CountDownLatch;
    2. import java.util.concurrent.ExecutorService;
    3. import java.util.concurrent.Executors;
    4. public class CountDownLatchExample {
    5. public static void main(String[] args) throws InterruptedException {
    6. int numThreads = 5;
    7. CountDownLatch latch = new CountDownLatch(numThreads);
    8. ExecutorService executor = Executors.newFixedThreadPool(numThreads);
    9. for (int i = 0; i < numThreads; i++) {
    10. executor.submit(() -> {
    11. System.out.println("Thread " + Thread.currentThread().getId() + " is working");
    12. try {
    13. Thread.sleep(1000);
    14. } catch (InterruptedException e) {
    15. e.printStackTrace();
    16. }
    17. System.out.println("Thread " + Thread.currentThread().getId() + " has finished");
    18. latch.countDown(); // 减少计数器
    19. });
    20. }
    21. latch.await(); // 等待所有线程完成
    22. System.out.println("All threads have finished");
    23. executor.shutdown();
    24. }
    25. }

    在这个例子中,我们创建了一个CountDownLatch,其计数器初始化为线程数。每个工作线程在完成任务后调用countDown()方法,主线程通过await()方法等待所有线程完成。

    2. Phaser

    Phaser是一个更灵活的同步屏障,它允许多个阶段的多线程同步。Phaser可以动态地注册和注销参与者,非常适合需要多阶段同步的场景。

    代码示例:
    1. import java.util.concurrent.Phaser;
    2. import java.util.concurrent.ExecutorService;
    3. import java.util.concurrent.Executors;
    4. public class PhaserExample {
    5. public static void main(String[] args) {
    6. Phaser phaser = new Phaser(1); // 注册主线程作为参与者
    7. ExecutorService executor = Executors.newFixedThreadPool(5);
    8. for (int i = 0; i < 5; i++) {
    9. executor.submit(() -> {
    10. System.out.println("Thread " + Thread.currentThread().getId() + " is starting phase 1");
    11. phaser.arriveAndAwaitAdvance(); // 通知阶段完成并等待其他线程
    12. try {
    13. Thread.sleep(1000);
    14. } catch (InterruptedException e) {
    15. e.printStackTrace();
    16. }
    17. System.out.println("Thread " + Thread.currentThread().getId() + " is starting phase 2");
    18. phaser.arriveAndAwaitAdvance(); // 通知阶段完成并等待其他线程
    19. });
    20. }
    21. // 主线程等待所有线程完成第一阶段
    22. phaser.arriveAndAwaitAdvance();
    23. System.out.println("All threads have finished phase 1");
    24. // 主线程等待所有线程完成第二阶段
    25. phaser.arriveAndAwaitAdvance();
    26. System.out.println("All threads have finished phase 2");
    27. executor.shutdown();
    28. }
    29. }

    在这个例子中,我们创建了一个Phaser,并注册了主线程作为初始参与者。每个工作线程在完成每个阶段后调用arriveAndAwaitAdvance()方法,主线程也参与同步,确保所有线程在进入下一阶段前都已完成当前阶段。

    总结

    CountDownLatchPhaser都是Java并发编程中非常有用的同步工具。CountDownLatch适用于简单的等待-完成场景,而Phaser提供了更灵活的多阶段同步机制。通过合理使用这些工具,我们可以有效地管理多线程环境下的同步问题,提高程序的性能和可靠性。希望这些示例和解释能帮助新人更好地理解和应用这些高级同步机制。

  • 相关阅读:
    猿创征文|设计模式之享元模式的理解
    对本地存储的有效期的理解
    运营︱内容营销怎么做?
    深入源码剖析String类为什么不可变?(还不明白就来打我)
    MFC---C++
    ajax请求出错自动重发
    UI基础——UGUI源码架构
    中国传统节日春节网页HTML代码 春节大学生网页设计制作成品下载 学生网页课程设计期末作业下载 DW春节节日网页作业代码下载
    Python之CrawlSpider
    C++的动态内存分配
  • 原文地址:https://blog.csdn.net/weixin_53840353/article/details/140003672