用JAVA写一个perterson算法
时间: 2024-05-16 10:11:52 浏览: 20
Sure, here is an example implementation of the Peterson algorithm in Java:
```java
class Peterson {
private volatile boolean[] flag = new boolean[2];
private volatile int victim;
public void lock(int threadId) {
int i = threadId;
int j = 1 - i;
flag[i] = true;
victim = i;
while (flag[j] && victim == i) {}
}
public void unlock(int threadId) {
flag[threadId] = false;
}
}
```
In this implementation, the `lock` method is used to acquire the lock, and the `unlock` method is used to release it. The algorithm ensures that at most one thread is in its critical section at any given time.
I hope this helps! Let me know if you have any other questions.