Thread Synchronization (1)

Source: Internet
Author: User
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 );
}
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.