Guest User

Untitled

a guest
Oct 23rd, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. using System;
  2. using System. Collections.Generic ;
  3. using System. Linq;
  4. using System. Text;
  5. using System. Threading;
  6.  
  7. namespace ConsoleApplication3
  8. {
  9. class Program
  10. {
  11. private static readonly object _lockObject = new object();
  12. private static int _number = 0 ;
  13.  
  14. static void Main( string[] args )
  15. {
  16. //for (int i = 0; i < 10; i++)
  17. //{
  18. // new Thread(() =>
  19. // {
  20. // for (int j = 0; j < 3; )
  21. // {
  22. // Monitor.Enter(_lockObject);
  23. // Console.WriteLine(_number);
  24. // _number++;
  25. // Monitor.Exit(_lockObject);
  26. // j++;
  27. // }
  28.  
  29. // }).Start();
  30.  
  31. //}
  32. Thread thead1 = new Thread(Run1);
  33. Thread thead2 = new Thread(Run2);
  34. Thread thead3 = new Thread(Run3);
  35.  
  36. thead1.Start ();
  37. thead2.Start ();
  38. thead3.Start ();
  39.  
  40. }
  41.  
  42. private static void Run1()
  43. {
  44. for (int i = 0; i < 10; )
  45. {
  46. Monitor. Enter(_lockObject );
  47. if (_number % 3 == 0)
  48. {
  49. Console. WriteLine("a" );
  50. _number++;
  51. i++;
  52.  
  53. }
  54. Monitor. Exit(_lockObject );
  55. }
  56.  
  57. }
  58.  
  59. private static void Run2()
  60. {
  61. for (int i = 0; i < 10; )
  62. {
  63. Monitor. Enter(_lockObject );
  64. if (_number % 3 == 1)
  65. {
  66. Console. WriteLine("b" );
  67. _number++;
  68. i++;
  69.  
  70. }
  71. Monitor. Exit(_lockObject );
  72. }
  73. }
  74.  
  75. private static void Run3()
  76. {
  77. for (int i = 0; i < 10; )
  78. {
  79. Monitor. Enter(_lockObject );
  80. if (_number % 3 == 2)
  81. {
  82. Console. WriteLine("c" );
  83. _number++;
  84. i++;
  85.  
  86. }
  87. Monitor. Exit(_lockObject );
  88. }
  89. }
  90.  
  91. }
  92. }
Add Comment
Please, Sign In to add comment