Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.87 KB | None | 0 0
  1. package mk.ukim.finki.os.synchronization.exam14.march;
  2.  
  3. import java.util.Date;
  4. import java.util.HashSet;
  5. import java.util.Scanner;
  6. import java.util.concurrent.Semaphore;
  7.  
  8. import mk.ukim.finki.os.synchronization.ProblemExecution;
  9. import mk.ukim.finki.os.synchronization.TemplateThread;
  10.  
  11. public class CalciumNitride {
  12. public static Semaphore Ca;
  13. public static Semaphore n;
  14. public static Semaphore ntuka;
  15. public static Semaphore mozeBond;
  16. public static Semaphore lock;
  17.  
  18. static int count;
  19.  
  20. public static void init() {
  21. Ca = new Semaphore(3);
  22. n = new Semaphore(2);
  23. ntuka = new Semaphore(0);
  24. mozeBond = new Semaphore(0);
  25. lock = new Semaphore(1);
  26.  
  27.  
  28. count = 0 ;
  29. }
  30.  
  31. public static class Calcium extends TemplateThread {
  32.  
  33. public Calcium(int numRuns) {
  34. super(numRuns);
  35. }
  36.  
  37. @Override
  38. public void execute() throws InterruptedException {
  39. Ca.acquire();
  40. lock.acquire();
  41. if(count == 2){
  42. lock.release();
  43. ntuka.acquire(2);
  44. mozeBond.acquire(4);
  45. state.bond();
  46. state.validate();
  47. count = 0;
  48. Ca.release(3);
  49. n.release(2);
  50. }
  51. else{
  52. count++;
  53. lock.release();
  54. mozeBond.release();
  55. state.bond();
  56. }
  57.  
  58.  
  59. }
  60. }
  61.  
  62. public static class Nitrogen extends TemplateThread {
  63.  
  64. public Nitrogen(int numRuns) {
  65. super(numRuns);
  66. }
  67.  
  68. @Override
  69. public void execute() throws InterruptedException {
  70. n.acquire();
  71. ntuka.release();
  72. mozeBond.release();
  73. state.bond();
  74. }
  75. }
  76. static CalciumNitrideState state = new CalciumNitrideState();
  77.  
  78. public static void main(String[] args) {
  79. for (int i = 0; i < 10; i++) {
  80. run();
  81. }
  82. }
  83.  
  84. public static void run() {
  85. try {
  86. Scanner s = new Scanner(System.in);
  87. int numRuns = 1;
  88. int numIterations = 100;
  89. s.close();
  90.  
  91. HashSet<Thread> threads = new HashSet<Thread>();
  92.  
  93. for (int i = 0; i < numIterations; i++) {
  94. Nitrogen n = new Nitrogen(numRuns);
  95. threads.add(n);
  96. Calcium ca = new Calcium(numRuns);
  97. threads.add(ca);
  98. ca = new Calcium(numRuns);
  99. threads.add(ca);
  100. n = new Nitrogen(numRuns);
  101. threads.add(n);
  102. ca = new Calcium(numRuns);
  103. threads.add(ca);
  104. }
  105.  
  106. init();
  107.  
  108. ProblemExecution.start(threads, state);
  109. System.out.println(new Date().getTime());
  110. } catch (Exception ex) {
  111. ex.printStackTrace();
  112. }
  113. }
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement