Java multithreading guide for beginners (12): Use synchronized block to synchronize Variables

Source: Internet
Author: User

We can use the synchronized block to synchronize specific static or non-static methods. To implement this requirement, you must define a class variable for the methods of these features, then enclose the code of these methods in the synchronized block, and pass the class variable as a parameter to the synchronized block. The following code demonstrates how to synchronize specific class methods:

001 package mythread;
002
003 public class syncthread extends thread
004 {
005 Private Static string sync = "";
006 private string methodtype = "";
007
008 Private Static void method (string S)
009 {
010 synchronized (Sync)
011 {
012 sync = s;
013 system. Out. println (s );
014 while (true );
015}
016}
017 public void Method1 ()
018 {
019 method ("Method1 ");
020}
021 public static void staticmethod1 ()
022 {
023 method ("staticmethod1 ");
024}
025 public void run ()
026 {
027 if (methodtype. Equals ("static "))
028 staticmethod1 ();
029 else if (methodtype. Equals ("nonstatic "))
030 Method1 ();
031}
032 public syncthread (string methodtype)
033 {
034 this. methodtype = methodtype;
035}
036 public static void main (string [] ARGs) throws exception
037 {
038 syncthread sample1 = new syncthread ("nonstatic ");
039 syncthread sample2 = new syncthread ("static ");
040 sample1.start ();
041 sample2.start ();
042}
043}

The running result is as follows:

Method1
Staticmethod1

Many readers may be surprised to see the above running results. In the above Code, the Method1 and staticmethod1 methods use static string variable sync for synchronization. These two methods can only be executed at the same time, and both of them will execute an infinite loop Statement of rows. Therefore, the output result can only be one of Method1 and staticmethod1. But this program outputs both strings.

The willingness to see such a result is very simple. Let's take a look at the 012 lines. It turns out that the sync value has changed in this line. Here we will talk about the string type in Java. The string type is different from other complex types in Java. When a string type variable is used, Java creates a new string type instance by assigning a value to this variable. The following code is used:

String S = "hello ";
System. Out. println (S. hashcode ());
S = "world ";
System. Out. println (S. hashcode ());

In the above Code. The hashcode value of the first s is different from that of the second after the second value is assigned. Because you do not need to use new to create a string-type instance, do not assign values to this variable when synchronizing string-type variables. Otherwise, the variables cannot be synchronized.

Since a new instance has been created for sync in line 013, assuming Method1 is executed first, after the Method1 method executes the Code in line 013, the sync value is not the original value, and the Method1 method is still locked by the initial value of the sync variable. At this moment, staticmethod1 is executed to synchronized (Sync). The sync to be locked in the staticmethod1 method is no longer the sync to be locked in the Method1 method. Therefore, the synchronization of the two methods has been damaged.

To solve the problem above, remove line 013. In this example, we add this line to demonstrate that if you change the value of the Synchronized Variable in the synchronized block when using class variables to synchronize methods, the synchronization between methods will be broken. To completely avoid this, you can use the final keyword when defining synchronization variables. For example, you can change the line 005 in the above program to the following format:

Private Final Static string sync = "";

After the final keyword is used, sync can only assign values to it during definition and cannot be modified later. If sync is assigned a value elsewhere in the program, the program cannot be compiled. In eclipse and other development tools, a prompt will be provided directly in the wrong place.

We can understand synchronized blocks from two perspectives. If you understand it from the perspective of class methods, you can use class variables to synchronize the corresponding methods. From the perspective of class variables, you can use the synchronized block to ensure that a class variable can only be accessed by one method at the same time. From any angle, they are essentially the same, that is, they use class variables to obtain synchronization locks and implement synchronization through mutual exclusion of synchronization locks.

Note: when using the synchronized block, note that the synchronized block can only use an object as its parameter. For simple variables (such as int, Char, and Boolean), synchronized cannot be used for synchronization.

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.