Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System. Collections.Generic ;
- using System. Linq;
- using System. Text;
- using System. Threading;
- namespace ConsoleApplication3
- {
- class Program
- {
- private static readonly object _lockObject = new object();
- private static int _number = 0 ;
- static void Main( string[] args )
- {
- //for (int i = 0; i < 10; i++)
- //{
- // new Thread(() =>
- // {
- // for (int j = 0; j < 3; )
- // {
- // Monitor.Enter(_lockObject);
- // Console.WriteLine(_number);
- // _number++;
- // Monitor.Exit(_lockObject);
- // j++;
- // }
- // }).Start();
- //}
- Thread thead1 = new Thread(Run1);
- Thread thead2 = new Thread(Run2);
- Thread thead3 = new Thread(Run3);
- thead1.Start ();
- thead2.Start ();
- thead3.Start ();
- }
- private static void Run1()
- {
- for (int i = 0; i < 10; )
- {
- Monitor. Enter(_lockObject );
- if (_number % 3 == 0)
- {
- Console. WriteLine("a" );
- _number++;
- i++;
- }
- Monitor. Exit(_lockObject );
- }
- }
- private static void Run2()
- {
- for (int i = 0; i < 10; )
- {
- Monitor. Enter(_lockObject );
- if (_number % 3 == 1)
- {
- Console. WriteLine("b" );
- _number++;
- i++;
- }
- Monitor. Exit(_lockObject );
- }
- }
- private static void Run3()
- {
- for (int i = 0; i < 10; )
- {
- Monitor. Enter(_lockObject );
- if (_number % 3 == 2)
- {
- Console. WriteLine("c" );
- _number++;
- i++;
- }
- Monitor. Exit(_lockObject );
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment