zoukankan      html  css  js  c++  java
  • CountDownLatch CyclicBarrier Semaphore

    如下是简单的线程

    for (int i = 0; i <10 ; i++) {
         new Thread(()->{
            System.out.println("1");
              },""+i).start();
          }
       System.out.println("2");

    2在线程代码后 但不会在线程执行完后才跑

    CountDownLatch(减计数器)
    CountDownLatch countDownLatch = new CountDownLatch(8);//初始化计数器值
            for (int i = 0; i < 8; i++) {
                new Thread(()->{
                    System.out.println("1");
                    countDownLatch.countDown();//数量-1
                }).start();
            }
            countDownLatch.await();//等待 计数器归0后往下走
            System.out.println("2");

    CountDownLatch减计数 计数器不为0休眠等待  归0后唤醒(也是一个线程)





    CyclicBarrier(加计数器)
     CyclicBarrier cyclicBarrier = new CyclicBarrier(3,()->{
                System.out.println("数量达到3");
            });
            for (int i = 0; i < 3; i++) {
                int i1=i;
                new Thread(()->{
                    System.out.println("第"+i1+"个");
                    try {
                        cyclicBarrier.await();//等待并+1
                    } catch (Exception e) {
                        e.printStackTrace();
                    } 
                }).start();
            }

    指定个数线程跑完后再执行

    Semaphore(限流)(重点)
     Semaphore semaphore = new Semaphore(3);
            for (int i = 0; i < 9; i++) {
                new Thread(()->{
                    try {
                        semaphore.acquire();//获取
                        System.out.println("只能进来指定个数线程");
                        TimeUnit.SECONDS.sleep(2);//等待2s
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        semaphore.release();//释放
                    }
                }).start();
            }

    同一时间只能跑指定数量的线程

  • 相关阅读:
    js 数组详解(javascript array)
    CentOS 修改IP地址, DNS, 网关
    Leetcode 652.寻找重复的子树
    Leetcode 650.只有两个键的键盘
    Leetcode 649.Dota2参议院
    Leetcode 648.单词替换
    Leetcode 647.回文子串
    Leetcode 645.最长数对链
    Leetcode 643.子数组最大平均数I
    Leetcode 640.求解方程
  • 原文地址:https://www.cnblogs.com/hbhb/p/14342647.html
Copyright © 2011-2022 走看看