Advertisement
Guest User

Untitled

a guest
Jan 21st, 2020
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. import java.util.HashSet;
  2. import java.util.concurrent.Semaphore;
  3. public class KindergartenShow {
  4.  
  5. public static class Child extends Thread
  6. {
  7. private static Semaphore seats=new Semaphore(6);
  8. private static Semaphore canPlay=new Semaphore(0);
  9. private static Semaphore lock=new Semaphore(1);
  10. private static Semaphore newCycle=new Semaphore(0);
  11. int groupNo=0;
  12. int totalNo=0;
  13. int sumPermits=0;
  14. int numExecutions=0;
  15. int sumQueue=0;
  16. public Child (int numRuns)
  17. {
  18. super(String.valueOf(numRuns));
  19. }
  20.  
  21. public void execute () throws InterruptedException
  22. {
  23. seats.acquire();
  24. System.out.println("dete vleze");
  25. lock.acquire();
  26. groupNo++;
  27. if(groupNo==6)
  28. {
  29. canPlay.release(6);
  30. System.out.println("Pretstavata pocinja");
  31. }
  32. lock.release();
  33. canPlay.acquire(); // ova go vide
  34. lock.acquire();
  35. groupNo--; // ova go vide
  36. System.out.println("dete iskoci");
  37. totalNo++; // ova go vide
  38. if(groupNo==0)
  39. {
  40. seats.release(6); //cycleov go vide
  41. System.out.println("si idat decata");
  42. }
  43. //lock.release(); ova go napisa a ne treba
  44. if(totalNo==24)
  45. {
  46. newCycle.release(24);
  47. System.out.println("zavrsi cel ciklus");
  48. totalNo=0;
  49. }
  50. lock.release();
  51. newCycle.acquire();
  52. }
  53. }
  54.  
  55. public static void main(String [] args) throws InterruptedException {
  56. HashSet<Child> threads = new HashSet<>();
  57. for(int i=0;i<24;i++)
  58. {
  59. Child c=new Child(i);
  60. threads.add(c);
  61. }
  62. for(Child c: threads)
  63. {
  64. c.start();
  65. }
  66. for(Child c: threads)
  67. {
  68. c.join(2000);
  69. }
  70. for (Child c: threads)
  71. {
  72. if(c.isAlive())
  73. {
  74. c.interrupt();
  75. System.out.println("Possible deadlock");
  76. }
  77. }
  78. System.out.println("Pretstavata zavrsi");
  79. }
  80.  
  81.  
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement