About the Synchronized keyword in Java

Source: Internet
Author: User

"About the content"

This article mainly introduces how to use the Synchronized keyword in Java to implement the mutex of the thread correctly.

"Capacity Requirements"

At the very least, we have mastered the basics of Java syntax, basic object-oriented knowledge, and created and started threads.

Body

About the use of synchronized keyword, many of the saying is "Lock the same object" to ensure that the lock is normal, today, someone asked a question, I feel very good, so share with you.

Here, not to mention the basic use of threading and synchronized keywords, in a very traditional "bank to take money" story as a case, directly on the code:
Ps: The following code is directly knocked, not copied in the IDE tool, there may be a wrong place, please forgive me.

public class Threadsample {public    static object lock = new Object ();     public static int money = +;         public static void Main (String args) {         card card1 = new Card ();         Card Card2 = new card ();                 Card1.start ();         Card2.start ();     } } class Card extends Thread {public     void run () {         Synchronize (threadsample.lock) {             if (Threadsample.money & gt;=) {                 Threadsample.money-=;                 System.out.println ("Withdrawal successful, Balance:" + Threadsample.money);             } else {                 System.out.println ("Insufficient balance, withdrawal failed!") ");             }         }    }}

The above code is a mock-up, using static member money to represent the account, so that multiple threads are guaranteed access to the same value, while the static member is unique and has a shared attribute, using the static member lock in the above code for synchronized locking , this practice is feasible, so in many people's opinion, "lock is the same object can be locked".

However, someone has tested the following code and asked questions (ignoring the same code snippet):

Class Card extends Thread {public     Integer i = 1;         public void Run () {         Synchronize (i) {             if (Threadsample.money >=) {                 Threadsample.money-=;                 System.out.println ("Withdrawal successful, Balance:" + Threadsample.money);             } else {                 System.out.println ("Insufficient balance, withdrawal failed!") ");             }         }     } }

Write here, I have to say from the heart, he as a 1th time to learn the thread of the person, ask such a question, certainly is very good!

The above code declares the public integer i = 1 in the card, and uses this integer object as the object of the synchronized lock, and finally, the lock is successful.

If you refer to the previous "lock is the same object can be locked", then, from the code can be seen in the process of creating 2 card objects, then the 2 card objects have their own integer I member, the lock is not the same object, but also successfully locked, so, The previous statement is not appropriate!
It may be said that integer or similar wrapper class is very special, perhaps the corresponding int these basic data types are at work, then the following code is still feasible:

Class Card extends Thread {public     String str = "www.tedu.cn";         public void Run () {         Synchronize (str) {             if (Threadsample.money >=) {                 Threadsample.money-=;                 System.out.println ("Withdrawal successful, Balance:" + Threadsample.money);             } else {                 System.out.println ("Insufficient balance, withdrawal failed!") ");             }         }     } }

OK, with string can also be locked, it is not related to the basic data type, what will be the next explanation? Don't worry, just look at the code:

public class Threadsample {public static int money = 1000;         public static void Main (String args) {Integer i1 = 1;                 Integer i2 = 1;         Card card1 = new Card (i1);                 Card Card2 = new Card (I2);         Card1.start ();     Card2.start ();         }} class Card extends Thread {public Integer i;     Public Card (Integer i) {this.i = i; public void Run () {Synchronize (i) {if (Threadsample.money >=) {thre                 Adsample.money-= 800;             System.out.println ("Withdrawal success, Balance:" + Threadsample.money); } else {System.out.println ("Insufficient balance, withdrawal failed!")             "); }         }     } }

In the above code, a constructor with parameters is added to the card, the member integer I is assigned a value, and the member integer I is used to implement the lock, and before the thread is run, the integer i1 and integer i2 are declared to create the card object, the result, Lock-in is still possible.

If you are interested, you can replace the above code with the integer string, you can find that it is still feasible!

Here, it is clear that before running the thread, it is possible to declare different objects for creating a card object, whether it is an integer type or a string type!

So, how do you explain the problem? It may be thought that equals () and hashcode () are not equals () In contrast to true, and the Hashcode () value is the same. The idea is wrong, see the following code:

public class Threadsample {public     static int money = +;         public static void Main (String args) {         long timemillis = System.currenttimemillis ();                 Date D1 = new Date (timemillis);         Date D2 = new Date (timemillis);                 Card card1 = new card (d1);         Card Card2 = new Card (D2);                 Card1.start ();         Card2.start ();     } }

We all know that the date class is overriding Equals () and hashcode (), and that D1 and D2 in the code above represent exactly the same time, so the Equals () of D1 and D2 are true, and the Hashcode () return value is the same, but The above code does not succeed in the implementation of the lock!

After reading the above so tangled problem, finally summed up the answer, popular point: if you use = = To determine the result is true, it can be used for synchronize lock!

For example, when using a string test, declare the following 2 string types of data:

String str1 = "www.cnblogs.com"; String str2 = "www.cnblogs.com";

Use the above 2 objects to create a card, and declare the string member in the card for locking, the result is OK, but the following code does not:

String str1 = "www.cnblogs.com"; String str2 = ""; STR2 + = "www.cnblogs.com";

Although the constituent characters are the same, the STR1 is directly assigned with constants, the corresponding data is stored in the string constant pool, and str2 is finally calculated by the variable, which is the result of the run time, and the corresponding data will be in the heap memory, so The str1 and str2 references stored in the stack memory are not the same, that is, str1 = = Str2 The result is false, so the lock is a failure!

In the 1th code of the preceding string, the string constants are assigned to STR1 and str2 at compile time, because the strings in the string constant pool are unique, so the result of str1, str2 using = = will be true, as for the integer wrapper classes, The interior is implemented by a number of static members, based on the static characteristics, so the above code i1, i2 Use = = To determine the result will be true.

Therefore, about the synchronized lock object, the academic definition can be "object in the stack memory reference is the same, is the same object, it can be used for the lock", the popular expression is "use = = to determine that true can be used to lock", because use = = Judgment is actually the data stored in the stack memory.

Summary

For synchronized lock object, if there can be 2, and use = = To determine the result is true, it can be used for the lock!



If this article has insufficient or wrong place, welcome at any time to point out, if need to reprint, please indicate source, Thank you!

About the Synchronized keyword in Java

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.