MutexTypeD.java 520 B

1234567891011121314151617181920212223242526272829303132333435
  1. class MutexTypeD extends Mutex {
  2. private volatile int turn;
  3. private volatile boolean[] flag;
  4. MutexTypeD() {
  5. turn = 0;
  6. flag = new boolean[2];
  7. flag[0] = flag[1] = false;
  8. }
  9. public void p(int id) {
  10. int other = 1 - id;
  11. flag[id] = true;
  12. while (flag[other] == true) {
  13. if (turn == other) {
  14. flag[id] = false;
  15. while (turn == other) Thread.yield();
  16. flag[id] = true;
  17. }
  18. }
  19. }
  20. public void v(int id) {
  21. turn = 1 - id;
  22. flag[id] = false;
  23. }
  24. public String toString() {
  25. return "D";
  26. }
  27. }