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();
    }
    }
  • 相关阅读:
    关于页面的已终止操作
    Assembly Manifest 通俗简易手册
    C# Enumeration 使用
    打架必备!擒敌拳116动连贯动作 分解动作
    解决js中onMouseOut事件冒泡的问题
    DOM标准与IE的html元素事件模型区别
    vim编辑器
    linux常用的命令解释
    搭建本地仓库
    Linux系统虚拟机安装
  • 原文地址:https://www.cnblogs.com/zpp1234/p/13096561.html
Copyright © 2011-2022 走看看