Issues needing attention in using the Sync keyword synchronized in Java

Source: Internet
Author: User

In Java, the Synchronized keyword is used to control thread synchronization, that is, in a multithreaded environment, control synchronized code snippets are not executed concurrently by multiple threads. Synchronized can either be added to a piece of code or added to a method.

The point is, don't think it's all right to add synchronized to a method or snippet, and look at the following code:

Class Sync {public synchronized void Test () {System.out.println ("Test start:"); try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("Test End:");}} Class MyThread extends Thread {public void run () {Sync sync = new Sync (); Sync.test ();}} public class Main {public static void main (string[] args) {for (int i = 0; i < 3; i++) {Thread thread = new MyThread (); Thread.Start ();}}}

 

Operation Result:

Test start:

Test start:

Test start:

Test end:

Test end:

Test End:

As can be seen, the above program three threads, while running the Sync Class Test () method, although the test () method with synchronized, but still running at the same time, seemingly synchronized did not work.

Remove the synchronized on the test () method and add synchronized (this) inside the method:

public void Test () {synchronized (this) {System.out.println ("Test start:"); try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("Test End:");}}

Operation Result:

Test start:

Test start:

Test start:

Test end:

Test end:

Test end:

Everything is still so calm, did not see synchronized play a role.

In fact, synchronized (this) and the non-static synchronized method (as for the static Synchronized method) can only prevent multiple threads from executing simultaneous code snippets for the same object at the same time.

Back to the topic of this article: synchronized lock is the code or object. The answer is:synchronized locks the object in parentheses, not the code. For non-static synchronized methods, the lock is the object itself, which is this.

When synchronized locks an object, other threads, if they want to get the lock on the object, must wait for the thread to complete the release lock to lock the object again so that thread synchronization is achieved. Even if you have two different code snippets that lock the same object, neither snippet can run concurrently in a multithreaded environment.

So when we use the Synchronized keyword, we can narrow the scope of the code snippet as far as possible, can be added in the code snippet synchronization on the whole method is not synchronized. This is called reducing the granularity of the lock, which makes the code much more concurrent. The reason is based on the above thought, the lock code snippet is too long, other threads are not to wait a long time, and so the flowers are thanks. Of course, this paragraph is a digression, and the core idea of this article is not much related.

Looking at the code above, each thread has a new Sync class object, which produces three sync objects, and because it's not the same object, you can run the Synchronized method or code snippet at the same time.

To verify the above view, modify the code to allow three threads to use the same Sync object.

Class MyThread extends Thread {private Sync sync;public MyThread (sync sync) {this.sync = sync;} public void Run () {sync.test ();}} public class Main {public static void main (string[] args) {Sync sync = new Sync (), for (int i = 0; i < 3; i++) {Thread T Hread = new MyThread (sync); Thread.Start ();}}

  

Operation Result:

Test start:

Test end:

Test start:

Test end:

Test start:

Test end:

It can be seen that the synchronized at this time has played a role.

So, what do you do if you really want to lock this piece of code? That is, if the first piece of code, each thread new a Sync object, how to make the test method is not multithreaded execution.

The solution is also simple, just lock the same object is not OK. For example,lock the same fixed object in parentheses after synchronized , so that's OK. This is no problem, however, it is a lot of practice to let synchronized lock the class object corresponding to it .

Class Sync {public void Test () {synchronized (Sync.class) {System.out.println ("Test start:"); try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("Test End:");}}} Class MyThread extends Thread {public void run () {Sync sync = new Sync (); Sync.test ();}} public class Main {public static void main (string[] args) {for (int i = 0; i < 3; i++) {Thread thread = new MyThread (); Thread.Start ();}}}

  

  

Operation Result:

Test start:

Test end:

Test start:

Test end:

Test start:

Test end:

The above code uses synchronized (sync.class) to achieve the effect of global locking.

Finally, the static synchronized method, the static method can be called directly the class name plus the method name, the method cannot use this, so it does not lock this, but the class object, so thestatic synchronized method is also equivalent to a global lock, which is equivalent to locking the code snippet.

Issues needing attention in using the Sync keyword synchronized in Java

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.