Created
April 26, 2014 13:44
-
-
Save 0minus273/11320402 to your computer and use it in GitHub Desktop.
Peterson.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! I've found 2 mistakes:
should be:
Because thread id starts from 0.
And
flag[j] = true;
should beflag[i] = true;
.