public class SemaphoreTest {
public static void main(String
[] args
) {
Semaphore semaphore
= new Semaphore(3);
for(int i
=0;i
<6;i
++){
new Thread(()->{
try {
semaphore
.acquire();
System
.out
.println(Thread
.currentThread().getName()+"抢到了车位");
TimeUnit
.SECONDS
.sleep(2);
System
.out
.println(Thread
.currentThread().getName()+"离开了车位");
semaphore
.release();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}).start();
}
}
}
打印结果如下:
Thread-0抢到了车位
Thread-2抢到了车位
Thread-1抢到了车位
Thread-1离开了车位
Thread-2离开了车位
Thread-3抢到了车位
Thread-4抢到了车位
Thread-0离开了车位
Thread-5抢到了车位
Thread-3离开了车位
Thread-5离开了车位
Thread-4离开了车位
可以用于限流场景
转载请注明原文地址:https://ipadbbs.8miu.com/read-5563.html