java 是不直接支持 信號(hào)量的,我們必須自己來(lái)定義我們所需要的信號(hào)量
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
}
}
對(duì)要訪問(wèn)的同步資源進(jìn)行 同步計(jì)數(shù)控制,來(lái)達(dá)到同步訪問(wèn)資源的目的。