我试图用Java实现Peterson's algorithm,并创造了暂时实施彼得森锁在Java中
public class Peterson {
private volatile boolean[] flag = new boolean[2];
private volatile int victim;
public void lock(int id)
{
//System.out.println(id);
int i = id;
int j = 1 - id;
flag[i] = true;
victim = i;
while (flag[j] && victim == i) {};
}
public void unlock(int id)
{
flag[id] = false;
}
}
下面我得到了下面的代码来测试锁...
class Counter {
private int value;
public Counter(int c) {
value = c;
}
public int get()
{
return value;
}
public int getAndIncrement() {
return value++;
}
}
class Thread1 implements Runnable {
private Counter c;
private int id;
private List<Integer> values;
private Peterson lock;
public Thread1(Counter c, int id, List<Integer> values, Peterson l) {
this.c = c;
this.id = id;
this.values = values;
this.lock = l;
}
public void run() {
while (true)
{
lock.lock(id);
try {
try {
if (c.get() > 20000)
return;
int n = c.getAndIncrement();
values.add(n);
} catch (Exception e) {
e.printStackTrace();
}
}
finally {
lock.unlock(id);
}
}
}
}
public class Tmp {
public static void main(String[] args) throws IOException {
Counter c = new Counter(1);
Thread[] t = new Thread[2];
List<Integer> values = new ArrayList<Integer>();
Peterson l = new Peterson();
for (int i = 0; i < t.length; ++i) {
t[i] = new Thread(new Thread1(c, i, values, l));
t[i].start();
}
System.out.println(values.size());
}
}
虽然我期望System.out.println(values.size());
打印20000
它在每次运行打印不同的数字。为什么是这样?我做错了什么?
我不明白你的意思'barr'什么,我应该设置'unlock'中的'barr = true',在'lock'方法中怎么样? –
@mario你想行动*发生之前解锁之前*之后成功锁定一个动作,所以你只需要在锁是读了'barr'(将*用'volatile's只能保证在之前*发生相同的字段) –
由于'joing',我似乎得到了错误的结果。谢谢 :) –