java 信号量

来源:互联网 发布:win10电脑加速软件 编辑:程序博客网 时间:2024/05/17 13:40
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
}
}

对要访问的同步资源进行 同步计数控制,来达到同步访问资源的目的。

原创粉丝点击