使用场景:java
一个厕全部5个坑位,每来一我的都要占一个坑位,当5我的都占完了,后面的人只能等待。每当有一我的吃完饭,等待的其中一人就能够继续进入空的坑位。其余人继续等待。ui
Demo:code
public static void main(String[] args) { final Semaphore semaphore = new Semaphore(2); for (int i = 0; i < 5; i++) { new Thread(new Runnable() { public void run() { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + " 开始蹲坑...."); TimeUnit.SECONDS.sleep(5); System.out.println(Thread.currentThread().getName() + " 蹲坑结束..."); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } }).start(); } }
程序执行结果:
get
Thread-1 开始蹲坑.... Thread-0 开始蹲坑.... Thread-1 蹲坑结束... Thread-0 蹲坑结束... Thread-3 开始蹲坑.... Thread-2 开始蹲坑.... Thread-2 蹲坑结束... Thread-3 蹲坑结束... Thread-4 开始蹲坑.... Thread-4 蹲坑结束...