zoukankan      html  css  js  c++  java
  • Semaphore

    信号量主要用于两个目的:

    1.用于多个共享资源的互斥使用

    2.用于并发数的控制.

    import java.util.concurrent.Semaphore;
    import java.util.concurrent.TimeUnit;
    
    public class SemaphoreDemo {
        public static void main(String[] args) {
            Semaphore semaphore = new Semaphore(3);
            for (int i = 0; i <= 6; i++) {
                new Thread(() -> {
    
                    System.out.println(Thread.currentThread().getName() + "	 抢到车位");
                    try {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName());
                        try {
                            TimeUnit.SECONDS.sleep(3);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "	 停车三秒后离开车位");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        semaphore.release();
                    }
                }, String.valueOf(i)).start();
            }
        }
    }
    

      

  • 相关阅读:
    LINUX常见服务列表
    xinetd服务管理
    System V启动脚本启动的服务
    linux系统服务
    proc文件系统
    sar网络统计数据
    sar磁盘I/O统计数据
    sar-CPU统计数据
    linux性能监视工具sar
    考试认证
  • 原文地址:https://www.cnblogs.com/sunliyuan/p/12513858.html
Copyright © 2011-2022 走看看