Java multithreaded programming using synchronized block synchronization variables

Source: Internet
Author: User

We can synchronize specific static or non-static methods by synchronized blocks. To implement this requirement, you must define a class variable for the methods of these attributes, and then enclose the code of these methods in a synchronized block and pass the class variable as a parameter to the synchronized block.

The following code demonstrates how to synchronize a specific class method:

Copy CodeThe code is as follows:
Package mythread;

public class Syncthread extends Thread
{
private static String sync = "";
Private String Methodtype = "";

private static void Method (String s)
{
Synchronized (sync)
{
Sync = s;
System.out.println (s);
while (true);
}
}
public void Method1 ()
{
Method ("Method1");
}
public static void StaticMethod1 ()
{
Method ("StaticMethod1");
}
public void Run ()
{
if (Methodtype.equals ("Static"))
StaticMethod1 ();
else if (methodtype.equals ("nonstatic"))
Method1 ();
}
Public Syncthread (String methodtype)
{
This.methodtype = Methodtype;
}
public static void Main (string[] args) throws Exception
{
Syncthread sample1 = new Syncthread ("nonstatic");
Syncthread sample2 = new Syncthread ("Static");
Sample1.start ();
Sample2.start ();
}
}

The results of the operation are as follows:

Copy CodeThe code is as follows:
Method1
StaticMethod1

Many readers may be surprised to see the results of the above run. In the above code, the Method1 and StaticMethod1 methods use static string variable sync for synchronization. Both methods can have only one execution at a time, and both methods execute an infinite loop of 014 rows. As a result, the output can only be one of method1 and staticMethod1. But this program outputs both of these strings.
The willingness to come up with this kind of result is simple, so let's look at 012 lines and we'll know. It turns out that the value of sync in this row has changed. Here is the string type in Java. The string type differs from other complex types in Java. When you use a string variable, Java creates a new instance of string type whenever a value is assigned to the variable. As shown in the following code:

Copy CodeThe code is as follows:
String s = "Hello";
System.out.println (S.hashcode ());
s = "World";
System.out.println (S.hashcode ());

In the code above. The value of the hashcode of the first S and re-assigned S is not the same. Since the creation of an instance of the string class does not require the use of new, it is important to be careful not to assign a value to this variable when synchronizing a variable of type string, otherwise the variable cannot be synchronized.
Since a new instance has been created for sync on line 012, assuming that method1 executes first, when the Method1 method executes 013 lines of code, the value of sync is not the original value, and the Method1 method locks the value of the sync variable initially. At this point, staticMethod1 just executes to synchronized (sync), in the StaticMethod1 method to lock the sync and method1 method locked sync is not one, therefore, The synchronization of the two methods has been compromised.
The solution to the above problem is, of course, to remove 012 rows. Adding this line to this example is to show that synchronization between methods is broken if the value of the synchronization variable is changed in the synchronized block when the class variable is used to synchronize the method. To completely prevent this from happening, you can use the final keyword when defining a synchronization variable. If the above program 005 lines can be changed to the following form:

Copy CodeThe code is as follows:
Private final static String sync = "";

With the final keyword, sync can only be assigned a value when it is defined, and can no longer be modified at a later time. If you assign a value to sync elsewhere in the program, the program will not compile and pass. In development tools such as Eclipse, you will be prompted directly in the wrong place.
We can understand the synchronized block from two angles. If you understand it from the perspective of a class method, you can synchronize the corresponding method with class variables. If you understand from the perspective of a class variable, you can use the synchronized block to ensure that a class variable can be accessed by only one method at a time. Regardless of the angle to understand, they are essentially the same, that is, the use of class variables to obtain a synchronous lock, through the mutual exclusion of synchronization lock to achieve synchronization.
Note: When using the synchronized block, be aware that the synchronized block can only use the object as its argument. If it is a simple type of variable (such as int, Char, Boolean, and so on), you cannot use synchronized to synchronize.

Java multithreaded programming using synchronized block synchronization variables

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.