zoukankan      html  css  js  c++  java
  • countdownlatch和semaphore

    CountDownLatch:

    CountDownLatch允许一个或多个线程等待其他线程完成操作;

    CountDownLatch需要指定一个整数值,此值是线程将要等待的操作数,当减为0时,才会唤醒所有await的线程,一个countdownlatch只能用一次

    public class CountDown1 {
    static CountDownLatch c=new CountDownLatch(3);

    public static void main(String[] args) throws InterruptedException {
    new Thread(()->{
    try{
    System.out.println("我在干活");
    c.countDown();//干完就减1
    }catch (Exception e){
    e.printStackTrace();
    }
    }).start();


    new Thread(()->{
    try{
    System.out.println("我在干活1");
    c.countDown();//干完就减1
    }catch (Exception e){
    e.printStackTrace();
    }
    }).start();
    new Thread(()->{
    try{
    System.out.println("我在干活2");
    c.countDown();//干完就减1
    }catch (Exception e){
    e.printStackTrace();
    }
    }).start();
    c.await();//当C减为0时,才执行此条之后的代码 countdown的缺点是只能用一次,减为0之后就不能用了
    System.out.println("结束");
    }
    }
    //Semaphore控制只有多少线程同时访问一个资源,可以用来做限流
    public class Semaphore01 {
        static Semaphore semaphore = new Semaphore(5);
    public static void main(String[] args) {
    for(int i=0;i<20;i++){
    final int j=i;
    new Thread(()->{
    try{
    action(j);
    }catch (Exception e){
    e.printStackTrace();
    }
    }).start();
    }
    }
    public static void action(int j) throws InterruptedException {
    //每次只允许5个线程同时执行下面的代码块
    semaphore.acquire();
    System.out.println(j+"在京东秒杀");
    try{
    Thread.sleep(3000);
    }catch (Exception e){
    e.printStackTrace();
    }
    System.out.println(j+"秒杀成功");
    semaphore.release();
    }
    }
  • 相关阅读:
    2015总结篇
    Android应用性能优化实践
    Android国外学习资源汇总
    直接拿来用!十大Material Design开源项目
    selenium12-读取文件 excel
    selenium11-自动化练习读取文件txt
    selenium10-python3部分代码复习
    selenium09-自动化练习案例
    selenium08-测试用例模块化与数据分离
    selenium07-处理 alter 对话框
  • 原文地址:https://www.cnblogs.com/zpp1234/p/13096561.html
Copyright © 2011-2022 走看看