zoukankan      html  css  js  c++  java
  • Java并发组件三之Semaphore

    • 使用场景:常用于使用有限的资源,限制线程并发的最大数量。
      默认情况下,信号量是非公平性的(先等待先执行为公平。类似于买东西的时候大家排队付款,先来的先付款是公平的。但是这时候有人插队,那就是非公平的)

      设定信号量的最大个数:Semaphore semaphore=new Semaphore(3);
    1. 获取信号量:
    2. semaphore.acquire(); //获取信号量
    3. semaphore.acquire(3); //获取多个许可
    4. semaphore.tryAcquire(3); //尝试获取多个许可
    5. semaphore.tryAcquire(5, TimeUnit.SECONDS); //给定时间内获取许可
    6. 释放信号量:semaphore.release();

    代码:
    public class T11_TestSemaphore {
        public static void main(String[] args) {
            //Semaphore s = new Semaphore(2);
            Semaphore s = new Semaphore(2, true);
            //允许一个线程同时执行
            //Semaphore s = new Semaphore(1);
            new Thread(()->{
                try {
                    s.acquire();
                    System.out.println("T1 running...");
                    Thread.sleep(200);
                    System.out.println("T1 running...");
    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    s.release();
                }
            }).start();
            new Thread(()->{
                try {
                    s.acquire();
                    System.out.println("T2 running...");
                    Thread.sleep(200);
                    System.out.println("T2 running...");
                    s.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
  • 相关阅读:
    8、SpringBoot-CRUD默认访问的首页以及thyleaf的静态文件引入/WebMvcConfigurer / WebMvcConfigurationSupport
    7、springmvc的自动配置
    6、模板引擎
    5.对静态资源映射的规则
    文件的上传和下载
    python file operation
    python sys.argv[]
    python pydoc
    python compile
    python exec
  • 原文地址:https://www.cnblogs.com/Courage129/p/12726370.html
Copyright © 2011-2022 走看看