Advertisement
Guest User

Untitled

a guest
Nov 16th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.05 KB | None | 0 0
  1. package lab;
  2.  
  3. /*
  4. * To change this license header, choose License Headers in Project Properties.
  5. * To change this template file, choose Tools | Templates
  6. * and open the template in the editor.
  7. */
  8.  
  9.  
  10. import java.util.concurrent.Semaphore;
  11.  
  12. /**
  13. *
  14. * @author ZTI
  15. */
  16. public class SemaphoresABC {
  17.  
  18. private static final int COUNT = 10; //Number of letters displayed by threads
  19. private static final int DELAY = 5; //delay, in milliseconds, used to put a thread to sleep
  20.  
  21. private static final Semaphore a = new Semaphore(2, true);
  22. private static final Semaphore b = new Semaphore(0, true);
  23. private static final Semaphore c = new Semaphore(1, true);
  24.  
  25. public static void main(String[] args) {
  26. new A().start(); //runs a thread defined below
  27. new B().start();
  28. new C().start();
  29.  
  30. }
  31.  
  32. private static final class A extends Thread { //thread definition
  33.  
  34. @Override
  35. @SuppressWarnings("SleepWhileInLoop")
  36. public void run() {
  37. try {
  38. for (int i = 0; i < COUNT*2; i++) {
  39.  
  40. a.acquire(2);
  41. System.out.print("A ");
  42. b.release();
  43.  
  44. Thread.sleep(DELAY);
  45. }
  46. } catch (InterruptedException ex) {
  47. System.out.println("Ooops...");
  48. Thread.currentThread().interrupt();
  49. throw new RuntimeException(ex);
  50. }
  51. System.out.println("\nThread A: I'm done...");
  52. }
  53. }
  54.  
  55. private static final class B extends Thread {
  56.  
  57. @Override
  58. @SuppressWarnings("SleepWhileInLoop")
  59. public void run() {
  60. try {
  61. for (int i = 0; i < COUNT*2; i++) {
  62.  
  63. b.acquire();
  64. System.out.print("B ");
  65. a.release();
  66. c.release();
  67.  
  68. Thread.sleep(DELAY);
  69. }
  70. } catch (InterruptedException ex) {
  71. System.out.println("Ooops...");
  72. Thread.currentThread().interrupt();
  73. throw new RuntimeException(ex);
  74. }
  75. System.out.println("\nThread B: I'm done...");
  76. }
  77. }
  78.  
  79. private static final class C extends Thread {
  80.  
  81. @Override
  82. @SuppressWarnings("SleepWhileInLoop")
  83. public void run() {
  84. try {
  85. for (int i = 0; i < COUNT; i++) {
  86.  
  87. c.acquire(2);
  88. System.out.print("C ");
  89. a.release(2);
  90.  
  91. Thread.sleep(DELAY);
  92. }
  93. } catch (InterruptedException ex) {
  94. System.out.println("Ooops...");
  95. Thread.currentThread().interrupt();
  96. throw new RuntimeException(ex);
  97. }
  98. System.out.println("\nThread C: I'm done...");
  99. }
  100. }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement