理论:
![]()
Semaphore 是 synchronized 的加强版,作用是控制线程的并发数量
多个线程抢多个资源,下面案例是有六台车抢三个停车位
使用Semaphore的代码:
public class Demo {
public static void main(String[] args) throws Exception{
//模拟三个停车位
Semaphore semaphore = new Semaphore(3);
//模拟六台车
for (int i = 1; i <= 6; i++) {
new Thread(()->{
try {
semaphore.acquire();//减一
//semaphore.release();//加一
//semaphore.release(2);//加二
System.out.println(Thread.currentThread().getName()+"\t 抢到车位");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName()+"\t 停车2秒后离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
控制台:

本文通过实例演示了如何使用Semaphore来控制线程的并发数量,具体场景为六台车抢三个停车位,展示了Semaphore作为synchronized加强版的作用。
2531

被折叠的 条评论
为什么被折叠?



