• CountDownLatch与CyclicBarrier


    static class LatchRunner implements Runnable{
            CountDownLatch latch;
            
            public LatchRunner(CountDownLatch latch) {
                this.latch = latch;
            }

            @Override
            public void run() {
                try {
                    Thread.sleep(200L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
                System.out.println("LatchRunner finish.");
            }
            
        }
        
        static class BarrierRunner implements Runnable{
            CyclicBarrier barrier;
            
            public BarrierRunner(CyclicBarrier barrier) {
                this.barrier = barrier;
            }

            @Override
            public void run() {
                try {
                    Thread.sleep(200L);
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println("BarrierRunner finish.");
            }
            
        }

        public static void main(String[] args) throws Exception {    
            CountDownLatch latch = new CountDownLatch(2);
            Thread[] threads = {new Thread(new LatchRunner(latch)), new Thread(new LatchRunner(latch))};
            threads[0].start();
            threads[1].start();
            latch.await();
            System.out.println("main execute1");
            
            CyclicBarrier barrier = new CyclicBarrier(2);
            Thread[] threads2 = {new Thread(new BarrierRunner(barrier)), new Thread(new BarrierRunner(barrier))};
            threads2[0].start();
            threads2[1].start();
            System.out.println("main execute2");
        }

  • 相关阅读:
    等保评测是什么意思
    ElasticSearch在Java中的基本使用方式
    驱动开发:通过Async反向与内核通信
    Redis 线程模型
    【信息论与编码基础】第1章 绪论
    C语言笔试题
    力扣每日一题:1732. 找到最高海拔【简单模拟题,有点前缀和的样子】
    网络编程 WSAStartup
    阿里巴巴面试题- - -多线程&并发篇(二十三)
    2023App测试必掌握的核心测试:UI、功能测试
  • 原文地址:https://blog.csdn.net/treeclimber/article/details/125514985