Created
October 23, 2017 06:59
-
-
Save ZhangSen1/2787e6307de0c6226331d0d818463a58 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment