并发编程系列【Semaphore同时允许存在几个】

作用:同时允许存在指定的数量,类似组锁

常用场景:1.停车场一共有3个停车位,来了100辆车,这时,一次最多允许停3辆。

     2.系统最大能抗300个并发,只是后就最多设置信号量的值为300,保证服务不崩,能正常用。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

    static class Parking{
        //信号量
        private Semaphore semaphore;

        Parking(int count){
            semaphore = new Semaphore(count);//指定最大同时拥有锁的线程数量
        }

        public void park(){//停车
            try {
                //获取信号量
                semaphore.acquire();//获得锁  =>  相当于 lock方法
                //long time = (long) (Math.random() * 10);//随机时间停车
                System.out.println(Thread.currentThread().getName() + "进入停车场,停车" + 10 + "秒..." );
                Thread.sleep(5000);
                System.out.println(Thread.currentThread().getName() + "开出停车场...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();//释放锁  =>  相当于Unlock方法
            }
        }
    }

    static class Car implements Runnable {
        Parking parking ;

        Car(Parking parking){
            this.parking = parking;
        }

        @Override
        public void run() {
            parking.park();     //进入停车场
        }
    }

    public static void main(String[] args){
        Parking parking = new Parking(3);// 最大允许3个线程持有锁
        int threadnum = 100; //指定创建线程数量
        ExecutorService exec = Executors.newFixedThreadPool(threadnum);
        for(int i = 0 ; i < threadnum ; i++){
           exec.execute(new Car(parking));
        }
        exec.shutdown();
    }
}
原文地址:https://www.cnblogs.com/hujunwei/p/15659634.html