Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. public class Monitor {
  2. int count = 0;
  3. public synchronized void aa(int n){
  4. while (n > 0){
  5. try {
  6. count++;
  7. wait();
  8. n--;
  9. }catch (InterruptedException e){}
  10. }
  11. System.out.println("count before="+count);
  12. notifyAll();
  13. System.out.println("count after="+count);
  14. }
  15.  
  16. public static void main(String[]args){
  17. Monitor m = new Monitor();
  18. Thread t1 = new T(2, m);
  19. Thread t2 = new T(1, m);
  20. Thread t3 = new T(0, m);
  21. try{
  22. t1.start();
  23. t2.start();
  24. t3.start();
  25. } catch (Exception e){}
  26. }
  27. }
  28.  
  29.  
  30. class T extends Thread {
  31. private Monitor m;
  32. public int par;
  33.  
  34. public T(int par, Monitor m){
  35. this.m = m;
  36. this.par = par;
  37. }
  38.  
  39. @Override
  40. public void run() {
  41. m.aa(par);
  42. }
  43. }
  44.  
  45. t1 -> count++ (count is now 1), wait()
  46. t2 -> count++ (count is now 2), wait()
  47. t3 -> notifyAll() -> t2 wakes up.
  48. t2 -> notifyAll() -> t1 wakes up
  49. t1 -> count++ (count is now 3), wait().
  50.  
  51. count before=2
  52. count after=2
  53. count before=2
  54. count after=2
  55.  
  56. public class Monitor {
  57. int count = 0;
  58. public synchronized void aa(int n){
  59. while (n > 0){
  60. try {
  61. count++;
  62. wait();
  63. n--;
  64. }catch (InterruptedException e){}
  65. }
  66. System.out.println("count before="+count);
  67. notify();
  68. System.out.println("count after="+count);
  69. }
  70.  
  71. public static void main(String[]args){
  72. Monitor m = new Monitor();
  73. Thread t1 = new T(2, m);
  74. Thread t2 = new T(1, m);
  75. Thread t3 = new T(0, m);
  76. try{
  77. t1.start();
  78. t2.start();
  79. t3.start();
  80. } catch (Exception e){}
  81. }
  82. }
  83.  
  84.  
  85. class T extends Thread {
  86. private Monitor m;
  87. public int par;
  88.  
  89. public T(int par, Monitor m){
  90. this.m = m;
  91. this.par = par;
  92. }
  93.  
  94. @Override
  95. public void run() {
  96. m.aa(par);
  97. }
  98. }
  99.  
  100. t1 -> count++ (count is now 1), wait()
  101. t2 -> count++ (count is now 2), wait()
  102. t3 -> notify() -> t1 wakes up.
  103. t1 -> count++ (count is now 3) wait().
  104.  
  105. count before=2
  106. count after=2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement