Java multithreaded programming using the Synchronized Keyword synchronization class method

Source: Internet
Author: User

The simplest approach is to use the Synchronized keyword to synchronize the Run method, and see the following code as long as the Synchronized keyword is added between void and publicCopy CodeThe code is as follows:
Public synchronized void Run ()
{
}


As you can see from the code above, you can synchronize the Run method with the Synchronized keyword between void and public, that is, for an object instance of the same Java class, the Run method can only be called by one thread, and after the current run executes, To be called by other threads. Even if the current thread executes the yield method in the Run method, it just pauses. Because another thread cannot execute the Run method, it will eventually continue to be executed by the current thread. First look at the following code:
The Sychronized keyword is bound to only one object instance

Copy CodeThe code is as follows:
Class Test
{
Public synchronized void Method ()
{

}
}

public class Sync implements Runnable
{
Private test test;
public void Run ()
{
Test.method ();
}
Public Sync (test test)
{
This.test = test;
}
public static void Main (string[] args) throws Exception
{
Test test1 = new test ();
Test test2 = new test ();
Sync sync1 = new sync (test1);
Sync sync2 = new sync (test2);
New Thread (SYNC1). Start ();
New Thread (SYNC2). Start ();
}
}


The method methods in the test class are synchronous. However, the above code establishes two instances of the test class, so the method methods of Test1 and Test2 are executed separately. To synchronize the method, you must pass an instance of the same test class to its constructor when you create an instance of the Sync class, as shown in the following code:
Sync sync1 = new sync (test1);
Not only can you use synchronized to synchronize non-static methods, but you can also use synchronized to synchronize static methods. If you can define method methods as follows:

Copy CodeThe code is as follows:
Class Test
{
public static synchronized void method () {}
}

The object instance that establishes the test class is as follows:
Test test = new test ();
For static methods, as long as the Synchronized keyword is added, this method is synchronous, whether using Test.method (), or using Test.method () to invoke the method, methods are synchronous, There is no problem with multiple instances of non-static methods.
Single-piece (Singleton) mode in 23 design modes if the traditional method is not thread-safe, the following code is a thread-unsafe single-piece mode.

Copy CodeThe code is as follows:
Package test;

Thread-Safe Singleton mode
Class Singleton
{
private static Singleton sample;

Private Singleton ()
{
}
public static Singleton getinstance ()
{
if (sample = = null)
{
Thread.yield (); To amplify thread insecurity in singleton mode
Sample = new Singleton ();
}
return sample;
}
}
public class MyThread extends Thread
{
public void Run ()
{
Singleton Singleton = Singleton.getinstance ();
System.out.println (Singleton.hashcode ());
}
public static void Main (string[] args)
{
Thread threads[] = new THREAD[5];
for (int i = 0; i < threads.length; i++)
Threads[i] = new MyThread ();
for (int i = 0; i < threads.length; i++)
Threads[i].start ();
}
}


In the above code calls the yield method is to make a single-piece mode of thread insecurity, if the line is removed, the above implementation is still thread insecure, but the likelihood is much less.
The running results of the program are as follows:

Copy CodeThe code is as follows:
25358555
26399554
7051261
29855319
5383406


The above results may have all the same in different operating environments, but generally the output of these five lines will not be identical. From this output, it can be seen that the object instance obtained by the GetInstance method is five, not the one we expect. This is because when a thread executes the Thread.yield (), it gives the CPU resources to another thread. Because the statements that created the Singleton object instance are not executed when the thread is switched between threads, these are the if judgments, so there is a case for creating five object instances (four or three object instances may be created. This depends on how many threads have passed the if judgment before the singleton object is created, and may result in a different run each time.
To make the above single-piece mode thread-safe, just add the Synchronized keyword to the getinstance. The code is as follows:
public static synchronized Singleton getinstance () {}
There is, of course, an easier way to create a singleton object when defining a singleton variable, and the code is as follows:
Private static final Singleton sample = new Singleton ();
You can then return the sample directly in the GetInstance method. This approach is simple, but it is not known to be flexible in creating singleton objects in the GetInstance method. The reader can choose different methods to implement the single-piece mode according to the specific requirements.

There are four points to note when using the Synchronized keyword:

1. The synchronized keyword cannot be inherited.
Although you can use synchronized to define a method, synchronized is not part of the method definition, so the Synchronized keyword cannot be inherited. If a method in the parent class uses the Synchronized keyword, and the method is overridden in a subclass, the method in the subclass is not synchronized by default, and the Synchronized keyword must be explicitly added to this method of the subclass. Of course, the corresponding method in the parent class can also be called in the subclass method, so that although the methods in the subclass are not synchronous, the subclass calls the synchronization method of the parent class, so the subclasses ' methods are equivalent to synchronizing. The example code for both of these approaches is as follows:
Add the Synchronized keyword to the subclass method

Copy CodeThe code is as follows:
Class Parent
{
Public synchronized void Method () {}
}
Class Child extends Parent
{
Public synchronized void Method () {}
}

Calling the parent class's synchronization method in a subclass method

Copy CodeThe code is as follows:
Class Parent
{
Public synchronized void Method () {}
}
Class Child extends Parent
{
public void Method () {Super.method (); }
}

2. You cannot use the Synchronized keyword when defining an interface method.
3. The construction method cannot use the Synchronized keyword, but it can be synchronized using the synchronized block discussed under SectionTo.
4. Synchronized can be placed freely.
In the previous example, the Synchronized keyword was placed before the return type of the method. But this is not synchronized can be placed in a unique location. In non-static methods, synchronized can also be placed at the front of the method definition, in a static method, synchronized can be placed in front of static, the code is as follows:

Copy CodeThe code is as follows:
Public synchronized void Method ();
Synchronized public void method ();
public static synchronized void method ();
Public synchronized static void method ();
Synchronized public static void method ();

Note, however, that synchronized cannot be placed after the method return type, as the following code is wrong:

Copy CodeThe code is as follows:
public void synchronized method ();
public static void Synchronized method ();

The Synchronized keyword can only be used to synchronize methods and cannot be used to synchronize class variables, as the following code is also wrong.

Copy CodeThe code is as follows:
public synchronized int n = 0;
public static synchronized int n = 0;

Although using the Synchronized keyword synchronization method is the safest way to synchronize, using a large number of synchronized keywords can cause unnecessary resource consumption and performance loss. Although the synchronized lock is a method on the surface, the synchronized lock is actually a class. That is, if synchronized is used in non-static methods Method1 and METHOD2 definitions, METHOD2 cannot execute until the method1 is finished. Static and non-static methods are similar. However, static and non-static methods do not affect each other. Look at the following code:

Copy CodeThe code is as follows:
Package test;

public class MyThread1 extends Thread
{
Public String MethodName;

public static void Method (String s)
{
System.out.println (s);
while (true)

}
Public synchronized void Method1 ()
{
Method ("Non-static METHOD1 methods");
}
Public synchronized void Method2 ()
{
Method ("Non-static METHOD2 methods");
}
public static synchronized void Method3 ()
{
Method ("Static method3 Methods");
}
public static synchronized void Method4 ()
{
Method ("Static METHOD4 Methods");
}
public void Run ()
{
Try
{
GetClass (). GetMethod (MethodName). Invoke (this);
}
catch (Exception e)
{
}
}
public static void Main (string[] args) throws Exception
{
MyThread1 myThread1 = new MyThread1 ();
for (int i = 1; I <= 4; i++)
{
Mythread1.methodname = "Method" + string.valueof (i);
New Thread (MYTHREAD1). Start ();
Sleep (100);
}
}
}

The results of the operation are as follows:

Copy CodeThe code is as follows:
Non-static Method1 method
The static Method3 method

As you can see from the results above, METHOD2 and METHOD4 cannot run until method1 and Method3 are finished. Therefore, we can draw a conclusion that if you use the Synchronized keyword in a class to define a non-static method, it will affect all non-static methods defined with the Synchronized keyword. If you define a static method, all static methods defined in the class that use the Synchronized keyword are affected. This is a bit like a table lock in a data table, and when a record is modified, the system locks the entire table, so a large amount of this synchronization can reduce the performance of the program significantly.

Java multithreaded programming using the Synchronized Keyword synchronization class method

Related Article

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.