Semaphore用法

image

public class SemaphoreDemo {

	public static void main(String[] args) {
		
		//模拟3个停车位
		Semaphore semaphore = new Semaphore(3);
		
		//模拟6部汽车
		for (int i = 1; i <= 6; i++) {
			new Thread(() -> {
				try {
					semaphore.acquire();
					System.out.println(Thread.currentThread().getName() + "	抢到车位");
					TimeUnit.SECONDS.sleep(3);
					System.out.println(Thread.currentThread().getName() + "	停车3s后离开车位");
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					semaphore.release();
				}
			},"汽车" + i).start();
		}
	}
}

输出:

汽车2	抢到车位
汽车1	抢到车位
汽车3	抢到车位
汽车1	停车3s后离开车位
汽车2	停车3s后离开车位
汽车4	抢到车位
汽车3	停车3s后离开车位
汽车5	抢到车位
汽车6	抢到车位
汽车4	停车3s后离开车位
汽车5	停车3s后离开车位
汽车6	停车3s后离开车位
原文地址:https://www.cnblogs.com/kaka-qiqi/p/14953575.html