Mutex.java 877 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import java.util.concurrent.ThreadLocalRandom;
  2. public abstract class Mutex {
  3. static int maxIter = 10;
  4. static int minIter = 1;
  5. static int msWait = 350;
  6. public static void criticalSection(String mark) {
  7. try {
  8. int rdIter = ThreadLocalRandom.current().nextInt(minIter, maxIter + 1);
  9. System.out.println("^");
  10. for (int k = 0; k < rdIter; k++) {
  11. System.out.println(mark);
  12. Thread.sleep(msWait);
  13. }
  14. System.out.println("v");
  15. }
  16. catch (InterruptedException e) {
  17. // Nothing
  18. }
  19. }
  20. public static void nonCriticalSection() {
  21. try {
  22. int rdIter = ThreadLocalRandom.current().nextInt(minIter, maxIter + 1);
  23. Thread.sleep(rdIter * msWait);
  24. }
  25. catch (InterruptedException e) {
  26. // Nothing
  27. }
  28. }
  29. // Take ownership
  30. public abstract void p(int id);
  31. // Release ownership
  32. public abstract void v(int id);
  33. public abstract void describe();
  34. }