MutexTypeH.java 504 B

1234567891011121314151617181920212223242526272829303132333435
  1. class MutexTypeH extends Mutex {
  2. private volatile int turn;
  3. private volatile boolean[] flag;
  4. MutexTypeH() {
  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 (turn == other) {
  13. while (flag[other]) Thread.yield();
  14. turn = id;
  15. }
  16. }
  17. public void v(int id) {
  18. flag[id] = false;
  19. }
  20. public String toString() {
  21. return "H";
  22. }
  23. public void describe() {
  24. System.out.println("Mutex type H");
  25. }
  26. }