MutexTypeD.java 588 B

123456789101112131415161718192021222324252627282930313233343536373839
  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. public void describe() {
  28. System.out.println("Mutex type D");
  29. }
  30. }