Example of using monitor or lock for thread synchronization:
Using system;
Using system. Threading;
Namespace Test
{
Class program {
Static long counter = 1;
Static void main ()
{
Thread T1 = new thread (F1 );
Thread t2 = new thread (F1 );
T1.start ();
T2.start ();
T1.join ();
T2.join ();
If (counter! = 1048576)
Console. Read ();
}
Static void F1 ()
{
For (INT I = 0; I <10; I ++)
{
/** // Method 1:
/// In a multi-threaded program, there is no synchronization, so
/// There will be confusion.
Counter * = 2;
/** // Method 2:
/// Use monitor for synchronization, which can be used in multiple threads.
// Monitor. Enter (typeof (Program ));
// Try {counter * = 2 ;}
// Finally {monitor. Exit (typeof (Program ));}
/** // Method 3:
/// C # uses lock to replace enter and exit of monitor.
// Lock (typeof (Program) {counter * = 2 ;}
Console. writeline ("counter * 2 {0}", counter );
Thread. Sleep (10 );
}
}
}
}
Create a bat script and call this program 30 times. Run this script.
If method 1 is used, the script may stop somewhere. At this time, there must be confusion.
If method 2 or method 3 is used, the script will not stop. Multi-thread synchronization is correct.
Using system;
Using system. Threading;
Namespace Test
{
Class program {
Static long counter = 1;
Static object _ syncroot = new object ();
Static void main ()
{
Thread T1 = new thread (F1 );
Thread t2 = new thread (F1 );
T1.start ();
T2.start ();
T1.join ();
T2.join ();
If (counter! = 1048576)
Console. Read ();
}
Static void F1 ()
{
For (INT I = 0; I <10; I ++)
{
/** // Method 4:
Lock (_ syncroot) {counter * = 2 ;}
Console. writeline ("counter * 2 {0}", counter );
Thread. Sleep (10 );
}
}
}
}