Java: Multithreading < two > Sync

Source: Internet
Author: User

Because of the latency of multithreaded access and the randomness of threads, there are often problems with security when using multi-threading, which can be very serious once they occur. In order to solve this security problem, synchronized appeared.

Synchronized usage one, put in the method, must pass an object obj

synchronized (obj) {    // code that needs to be synchronized }

Synchronized usage two, put on the method, do not need to pass the object

 Public synchronized void Method () {    // all the code in the methods body is synchronized }

Example: The bank has a coffers, initially 0, one day there are two wealthy businessmen to deposit gold coins, each time each time to save 100 gold coins, no use of synchronized multithreaded code

classbank{Private intGold=0;  Public voidAddintnum) {        Try{Thread.Sleep (10); Gold+=num; }        Catch(Exception e) {System.out.println ("Bank internal error, suspended service!" "); System.exit (0); } System.out.println ("There's" +gold+ "gold in the vault.); }}classBusinessImplementsrunnable{PrivateBank B =NewBank ();  Public voidrun () { for(inti=0;i<3;i++) {B.add (100); }    }}classstoregold{ Public Static voidMain (string[] args) {Business B=NewBusiness (); Thread T1=NewThread (b, "Zhang San")); Thread T2=NewThread (b, "John Doe"));        T1.start ();    T2.start (); }}

At run time, it is possible to have 500 gold coins two times in the vault and so on error condition, the reason is that gold is not synchronized, there is a simultaneous use of a value case. You should add synchronization to the bank's Add method, as follows

classbank{Private intGold=0;  Public voidAddintnum) {        synchronized( This)        {            Try{Thread.Sleep (10); Gold+=num; }            Catch(Exception e) {System.out.println ("Bank internal error, suspended service!" "); System.exit (0); }} System.out.println ("There's" +gold+ "gold in the vault.); }}

Synchronized can also be added to the method, such a simple way of writing, but the content of synchronization is much more. The lock for the synchronization function is this.

classbank{Private intGold=0;  Public synchronized voidAddintnum) {        Try{Thread.Sleep (10); Gold+=num; }        Catch(Exception e) {System.out.println ("Bank internal error, suspended service!" "); System.exit (0); } System.out.println ("There's" +gold+ "gold in the vault.); }}

Although synchronization allows threads to be more secure in handling certain transactions, it can affect the rate at which programs run because each thread has more operations such as lock, wait, and release locks.

So what code needs to be synchronized?

1, clear which code is multithreaded run code

2, clear sharing of data

3, clear which statements in multithreaded run code are operations that share data

What locks are used for synchronization?

1, the lock used by the function is this

2, the lock used by the static function is the class name. class, byte-code file object

Java: Multithreading < two > Sync

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.