java 是不直接支持 信號量的,我們必須自己來定義我們所需要的信號量
class Semaphore {
private int count;
public Semaphore(int count) {
this.count = count;
}
public synchronized void acquire() {
while(count == 0) {
try {
wait();
} catch (InterruptedException e) {
//keep trying
}
}
count--;
}
public synchronized void release() {
count++;
notify(); //alert a thread that´s blocking on this semaphore
}
}
對要訪問的同步資源進行 同步計數控制,來達到同步訪問資源的目的。