Semaphore概念及使用场景举例

信号量

Semaphore 是JDK1.5的 java.util.concurrent 并发包中提供的一个并发工具类。
	所谓 Semaphore 即 信号量 的意思。
	这个叫法并不能很好地表示它的作用,更形象的说法应该是 许可证管理器 。
	
	Semaphore 是一个计数信号量。
	
	从概念上将,Semaphore 包含一组许可证。
	如果有需要的话,每个 acquire() 方法都会阻塞,直到获取一个可用的许可证。
	每个 release() 方法都会释放持有许可证的线程,并且归还 Semaphore 一个可用的许可证。
	然而,实际上并没有真实的许可证对象供线程使用,Semaphore 只是对可用的数量进行管理维护。

场景:停车场2个车位,6辆车想停,前2辆停完离开后,后2辆才能进入。

public class SemaPhoreDemo {
	public static 	ExecutorService threadPool = Executors.newCachedThreadPool();
	public static final int cars = 6;
	public static final int part = 2;
	public static void main(String[] args) {
		CountDownLatch latch = new CountDownLatch(cars);
		Semaphore semaphore = new Semaphore(part, false);
		for(int i=0; i<cars; i++) {
			final int j = i;
			threadPool.execute(()->{
				try {
					semaphore.acquire();
					System.out.println("car "+j+" 进入停车位 
");
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}finally {
					semaphore.release();
					latch.countDown();
					System.out.println("********* car "+j+" 离开停车位
");
				}
			});
		}
		try {
			latch.await();
			System.out.println("################### 所有车辆离开  ##################");
			threadPool.shutdown();
		} catch (InterruptedException e) {
		}
	}
}
经验分享 程序员 微信小程序 职场和发展