zoukankan      html  css  js  c++  java
  • 多线程-CountDownLatch,CyclicBarrier,Semaphore

    1.CountDownLatch

    代码如下:

    public class CountDownLatchDemo {
    
        public static void main(String[ ]args) throws InterruptedException {
            CountDownLatch countDownLatch = new CountDownLatch(6);
           for(int i= 0; i<6; i++) {
               new Thread(() -> {
                   System.out.println(Thread.currentThread().getName() +"号同学离开了教室---");
                   countDownLatch.countDown();
               },String.valueOf(i)).start();
           }
            countDownLatch.await();
           System.out.println(Thread.currentThread().getName()+ " 班长开始锁门了---");
        }
    }


    2.CyclicBarrier

    public class CyclicBarrierDemo {
    
        private static final Integer NUMBER= 7;
    
        public static void main(String[] args) {
            CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER,() -> {
                System.out.println("集齐7颗龙珠召唤神龙!");
            });
    
            for(int i =1; i<=7; i++) {
                new Thread(() -> {
                    try {
                        System.out.println(Thread.currentThread().getName() +" 颗龙珠被收集到了");
                        cyclicBarrier.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                },String.valueOf(i)).start();
            }
        }
    }


    3.Semaphore

    public class SemaphoreDemo {
        private static final Integer Number = 3;
    
        public static void main(String[ ]args)  {
    
            Semaphore semaphore = new Semaphore(Number);
            //模拟6辆汽车抢3个停车位
            for(int i = 1; i<= 6; i++ ) {
                new Thread(() -> {
                    try {
    
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() +" 号车抢到停车位!");
                        TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                        System.out.println(Thread.currentThread().getName() +" -----号车离开了停车位");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        semaphore.release();
                    }
                },String.valueOf(i)).start();
    
            }
        }
    }

  • 相关阅读:
    实现Runnable接口和继承Thread类的区别
    图的DFS和BFS
    图建模
    数据结构-图的基本知识和表示
    除自身以外的乘积数组(力扣第238题)
    MapReduce源码分析--Shuffle阶段
    转到博客园
    vue中使用剪切板插件 clipboard.js
    vue中使用vue-qrcode生成二维码
    h5中嵌入视频自动播放的问题
  • 原文地址:https://www.cnblogs.com/liuyi13535496566/p/15026797.html
Copyright © 2011-2022 走看看