(1). Description
This example demonstrates how to use the lock, interlocked, and monitor classes to perform thread-critical operations (mutex)
(2). Code
Using system;
Using system. Threading;
Using system. collections;
Namespace locks _ implement mutex operations in the critical section _
{
// Delegate Declaration (function signature)
Delegate string mymethoddelegate ();
Class myclass
{
Private Static arraylist arrlist = new arraylist ();
Private Static int I = 0;
Public static void add ()
{
// Method 1: implement with lock
// Lock (arrlist)
//{
// Arrlist. Add (I. tostring ());
// I ++;
//}
// Method 2: implement with interlicked class
// System. Threading. interlocked. increment (Ref I );
// Arrlist. Add (I. tostring ());
// Method 3: Use the monitor class
Try
{
// I. Unlimited time
// Stem. Threading. Monitor. Enter (arrlist );
// II. Obtain the exclusive lock at the specified time
If (system. Threading. Monitor. tryenter (arrlist, timespan. fromseconds (30) // obtain the exclusive lock of an object within 30 seconds. Flexible use can prevent deadlock
{// Avoid mutual waiting. You may not get the exclusive lock within a certain period of time.
// Occupy other exclusive locks (other exclusive locks that are waiting for them to be occupied are in the waiting state ),
// At this time, you can release the exclusive lock that you are occupying and try to get the exclusive lock of the desired object.
Arrlist. Add (I. tostring ());
I ++;
}
}
Catch
{
// Custom error handling code when an exception occurs
}
Finally
{
Monitor. Exit (arrlist); // The object must be released whether it is normal or an error occurs.
}
}
[Stathread]
Static void main (string [] ARGs)
{
Thread thread1 = new thread (New threadstart (ADD ));
Thread thread2 = new thread (New threadstart (ADD ));
Thread thread3 = new thread (New threadstart (ADD ));
Thread1.start ();
Thread2.start ();
Thread3.start ();
Console. Read ();
For (INT I = 0; I <arrlist. Count; I ++)
{
Console. writeline (arrlist [I]. tostring ());
}
Console. Read ();
}
}
}
The code in this example has been tested and runs properly!
(3) Sample download
Http://www.cnblogs.com/Files/ChengKing/ThreadExample.rar