public class SemaphoreDemo {
public static void main(String[] args) {
//三个停车位
Semaphore sp = new Semaphore(3);
//停六个汽车
for (int i = 1; i <=6 ; i++) {
new Thread(()->{
try {
sp.acquire();
System.out.println(Thread.currentThread().getName()
+"\t号车驶入停车位");
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()
+"\t号车驶出停车位");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
sp.release();
}
},String.valueOf(i)).start();
}
}
}
结果
1 号车驶入停车位
3 号车驶入停车位
2 号车驶入停车位
2 号车驶出停车位
1 号车驶出停车位
3 号车驶出停车位
5 号车驶入停车位
4 号车驶入停车位
6 号车驶入停车位
6 号车驶出停车位
5 号车驶出停车位
4 号车驶出停车位
原文:https://www.cnblogs.com/hpdblogs/p/12497350.html