Advertisement
Guest User

Untitled

a guest
May 21st, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.96 KB | None | 0 0
  1. package semaphores;
  2.  
  3. import java.util.concurrent.Semaphore;
  4.  
  5. public final class ABCwithSem {
  6.  
  7. private static final int COUNT = 30;
  8. private static int COUNTER = 0;
  9. private static final int STEP = 10;
  10. private static final Semaphore a = new Semaphore(0 ,true);
  11. private static final Semaphore b = new Semaphore(0, true);
  12. private static final Semaphore c = new Semaphore(0, true);
  13. private static final Semaphore d = new Semaphore(1, true);
  14. private static final Semaphore e = new Semaphore(0, true);
  15.  
  16.  
  17. public static void main(String[] args) {
  18. new A().start();
  19. new B().start();
  20. new C().start();
  21. new D().start();
  22. new E().start();
  23. }
  24.  
  25. private static final class A extends Thread {
  26.  
  27. @Override
  28. public void run() {
  29. try {
  30. for (int i = 0; i < COUNT; i++) {
  31.  
  32. a.acquire(2);
  33. myPrint("A ");
  34. c.release();
  35. }
  36. } catch (InterruptedException ex) {
  37. }
  38. }
  39. }
  40.  
  41. private static final class B extends Thread {
  42.  
  43. @Override
  44. public void run() {
  45. try {
  46. for (int i = 0; i < COUNT*2; i++) {
  47. b.acquire();
  48. myPrint("B ");
  49. a.release();
  50. }
  51. } catch (InterruptedException ex) {
  52. }
  53. }
  54. }
  55.  
  56. private static final class C extends Thread {
  57.  
  58. @Override
  59. public void run() {
  60. try {
  61. for (int i = 0; i < COUNT; i++) {
  62.  
  63. c.acquire();
  64. myPrint("C ");
  65.  
  66. b.release(2);
  67. }
  68. } catch (InterruptedException ex) {
  69. }
  70. }
  71. }
  72.  
  73.  
  74.  
  75. private static final class D extends Thread {
  76.  
  77. @Override
  78. public void run() {
  79. try {
  80. for (int i = 0; i < COUNT; i++) {
  81.  
  82. d.acquire();
  83. myPrint("D ");
  84.  
  85. c.release();
  86. }
  87. } catch (InterruptedException ex) {
  88. }
  89. }
  90. }
  91.  
  92.  
  93. private static final class E extends Thread {
  94.  
  95. @Override
  96. public void run() {
  97. try {
  98. for (int i = 0; i < COUNT; i++) {
  99.  
  100. d.acquire();
  101. myPrint("E ");
  102.  
  103. a.release();
  104. }
  105. } catch (InterruptedException ex) {
  106. }
  107. }
  108. }
  109.  
  110.  
  111.  
  112. private static synchronized void myPrint(String s) {
  113. COUNTER++;
  114. System.out.print(s);
  115. if (COUNTER == STEP) {
  116. COUNTER = 0;
  117. System.out.println();
  118. }
  119. }
  120.  
  121. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement