Skip to content

Instantly share code, notes, and snippets.

@0minus273
Created April 26, 2014 13:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 0minus273/11320402 to your computer and use it in GitHub Desktop.
Save 0minus273/11320402 to your computer and use it in GitHub Desktop.
Peterson.java
public class Peterson {
public volatile boolean[] flag = new boolean[2];
public volatile int victim;
public void lock() {
int i = Integer.parseInt(Thread.currentThread().getName().substring(7)) - 1;
int j = 1 - i;
flag[j] = true;
victim = i;
while (flag[j] && victim == i) {}; // wait
}
public void unlock() {
int i = Integer.parseInt(Thread.currentThread().getName().substring(7)) - 1;
flag[i] = false;
}
}
@Tokubara
Copy link

Tokubara commented Dec 5, 2022

Thank you! I've found 2 mistakes:

int i = Integer.parseInt(Thread.currentThread().getName().substring(7)) - 1;

should be:

int i = Integer.parseInt(Thread.currentThread().getName().substring(7));

Because thread id starts from 0.

And flag[j] = true; should be flag[i] = true;.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment