多线程之Semaphore

多线程之Semaphore

Semaphore (信号量)

Counting semaphores are used to control the number of activities that can access a certain resource or perform a given action at the same time

A degenerate case of a counting semaphore is a binary semaphore, a Semaphore with an initial count of one. A binary semaphore can be used as a mutex with nonreentrant locking semantics; whoever holds the sole permit holds the mutex.

Semaphore管理着一组许可permit,许可的初始数量通过构造函数设定。

  • 调用acquire()方法时,如果没有许可可用了,就将线程阻塞,等待有许可被归还了再执行。
  • 当执行完业务功能后,需要通过release()方法将许可证归还,以便其他线程能够获得许可证继续执行。

如果初始化了一个许可为1的Semaphore,那么就相当于一个不可重入的互斥锁(Mutex)。

例子

车场仅有3个停车位,停车位就是有限的共享资源,许可数为3

public class SemaphoreTest {
public static void main(String[] args) {
Parking parking = new Parking(3);// 只能停3辆车的停车场

for (int i = 0; i < 8; i++) {
// 每一个线程表示一辆车到停车场停车
new Thread() {
public void run() {
parking.park();// 进入停车场
};
}.start();
}
}

static class Parking {
private Semaphore semaphore;// 信号量

Parking(int count) {
semaphore = new Semaphore(count);
}

public void park() {
try {
semaphore.acquire();// 获取许可
long time = (long) (Math.random() * 10);
System.out.println(Thread.currentThread().getName() + "进入停车场,停车" + time + "秒...");
Thread.sleep(time);// 获取许可
System.out.println(Thread.currentThread().getName() + "开出停车场...");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
}

https://mp.weixin.qq.com/s?__biz=MzAxMjEwMzQ5MA==&mid=2448890836&idx=2&sn=6828a20fcb1c81684fc00fe2e3a100af&scene=21#wechat_redirect