基本上,我有一个要同步的方法(一次只能让一个线程进入),但是不允许这种特定做法使用synced关键字。相反,我决定创建一个信号量并将其值设置为1,因此就像互斥锁一样(我相信synced关键字对吗?)。
基本上,我的Semaphore类如下:
import java.util.*;
public class Semaphore
{
private int count = 0;
public Semaphore (int init_val) {
count = init_val;
}
public synchronized void P() {
count = count - 1;
while(count < 0) {
try {
wait();
} catch(InterruptedException e) {
}
}
}
public synchronized void V() {
count = count + 1;
notifyAll();
}
}
并且我在想要同步的方法中使用它(仅作为示例):
Semaphore s = new semaphore(1);
int x = 0;
public void add() {
s.P()
int x = x + 1;
System.out.println(x);
s.V()
}
我有100个线程调用add方法,但是由于某种原因,x的值是并发的,但没有按顺序递增(竞争条件)。我不确定自己在做什么错,有什么建议吗?