Java synchronized Keywords

Source: Internet
Author: User

In Java, the synchronized keyword is used in conjunction with an object's built-in lock to protect the code block from thread safety in a concurrent environment, allowing the protected code block to operate atomically.

The synchronized keyword can be used to decorate a method to protect all blocks of code within a method, and you can protect a specified block of code in the same way as synchronized (object 1). (Say here: Many books say synchronized can lock the object, I really do not want to say so, so I confuse the concept ... Because, the object built-in lock is already exist , not who adds it, "synchronized ( object 1)" I would like to explain: the thread executing to this need to get to (Hold) "Object 1" Object lock to execute the code in the synchronized block).

When multiple threads execute a synchronized protected code or method, the key to mutual exclusion is whether the synchronized is the same lock. Here are a few scenarios used by synchronized and analyze which object locks he holds separately (assuming these methods belong to class Salary):

1, synchronized modified non-static method: Hold Salary class instance of the object lock

2, synchronized modified static method: Hold the Salary.class object lock

3, synchronized ( object 1): object lock holding object 1

4, synchronized (this): Holds the object lock of the current object instance of the Salary class

5, synchronized (salary.class): hold salary.class object Lock

Here are a few programs to experiment with.

First, synchronized modified non-static method: Hold The object lock of Salary class instance

Concurrent Object Classes Salary:

public class Salary {public synchronized void method1 () {try {thread.sleep ()} catch (Interruptedexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "have entered method1 at:" +system.currenttimemillis ()/1000);} public void Method2 () {System.out.println (Thread.CurrentThread (). GetName () + "have entered method2 at:" + System.currenttimemillis ()/1000);}}

Concurrent Program Synchronizetest:

Public class synchronizetest {public static void main (String[] args)  { Final salary salary = new salary (); Thread t1 = new thread (new runnable ()  {@Overridepublic  void run ()  {system.out.println (Thread.CurrentThread (). GetName () + " start at:" +system.currenttimemillis ()/ ); Salary.method1 (); System.out.println (Thread.CurrentThread (). GetName () + " end at:" +system.currenttimemillis ()/1000);}); T1.start ();//To ensure that the thread T1 first obtains the object lock, where the main thread hangs for 1 seconds, and then executes the code behind the boot thread t2. Try {thread.sleep (1000);}  catch  (interruptedexception e)  {e.printstacktrace ();} If thread T2 enters Salary.method2 () after 4 seconds of startup, then the same object lock is requested. Otherwise, it is not the same object lock Thread t2 = new thread (new runnable ()  {@Overridepublic  void  run ()  {system.out.println (Thread.CurrentThread (). GetName () + " start at:" + System.currenttimemillis ()/1000);synchronized  (Salary)  { //TODO1SALARY.METHOD2 ();} System.out.println (Thread.CurrentThread (). GetName () + " end at:" +system.currenttimemillis ()/1000);}); T2.start ();}}

Operation Result:

Thread-0 Start at:1452076058

Thread-1 Start at:1452076059

Thread-0 has entered Method1 at:1452076063

Thread-0 End at:1452076063

Thread-1 has entered Method2 at:1452076063

Thread-1 End at:1452076063


As can be seen from the running results, when the thread T1 into the method method1 5 seconds (releasing the object lock), the thread T2 enters the method method2, stating that two threads hold the same object lock.


Second, synchronized modified static method: Hold salary.class object Lock

Concurrent Object class Salary

public class Salary {public synchronized static void Method1 () {try {thread.sleep ()} catch (Interruptedexception e) {/ /TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "have entered method1 at:" +system.currenttimemillis ()/1000);} public void Method2 () {System.out.println (Thread.CurrentThread (). GetName () + "have entered method2 at:" + System.currenttimemillis ()/1000);}}

Concurrent Program Synchronizetest

Public class synchronizetest {public static void main (String[] args)  { Final salary salary = new salary (); Thread t1 = new thread (new runnable ()  {@Overridepublic  void run ()  {system.out.println (Thread.CurrentThread (). GetName () + " start at:" +system.currenttimemillis ()/ 1000); Salary.method1 (); System.out.println (Thread.CurrentThread (). GetName () + " end at:" +system.currenttimemillis ()/1000);}); T1.start ();//To ensure that the thread T1 first obtains the object lock, where the main thread hangs for 1 seconds, and then executes the code behind the boot thread t2. Try {thread.sleep (1000);}  catch  (interruptedexception e)  {e.printstacktrace ();} If thread T2 enters Salary.method2 () after 4 seconds of startup, then the same object lock is requested. Otherwise, it is not the same object lock Thread t2 = new thread (new runnable ()  {@Overridepublic  void  run ()  {system.out.println (Thread.CurrentThread (). GetName () + " start at:" + System.currenttimemillis ()/1000);synchronized  (salary.class)  {saLARY.METHOD2 ();} System.out.println (Thread.CurrentThread (). GetName () + " end at:" +system.currenttimemillis ()/1000);}); T2.start ();}}

Operation Result:

Thread-0 Start at:1452076058

Thread-1 Start at:1452076059

Thread-0 has entered Method1 at:1452076063

Thread-0 End at:1452076063

Thread-1 has entered Method2 at:1452076063

Thread-1 End at:1452076063


Iii. synchronized ( object 1): Object lock holding object 1

Concurrent Object Classes Salary:

public class Salary {private Object lock = new Object ();p ublic Salary (Object lock) {This.lock = lock;} public void Method1 () {synchronized (lock) {try {thread.sleep ()} catch (Interruptedexception e) {//TODO Auto-generat Ed catch Blocke.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "have entered method1 at:" +system.currenttimemillis ()/1000);}} public void Method2 () {System.out.println (Thread.CurrentThread (). GetName () + "have entered method2 at:" + System.currenttimemillis ()/1000);}}

Concurrent Program Synchronizetest:

Public class synchronizetest {public static void main (String[] args)  { final object  Object 1 = new object ();final salary salary = new  Salary (object 1); Thread t1 = new thread (new runnable ()  {@Overridepublic  void run ()  {system.out.println (Thread.CurrentThread (). GetName () + " start at:" +system.currenttimemillis ()/ ); Salary.method1 (); System.out.println (Thread.CurrentThread (). GetName () + " end at:" +system.currenttimemillis ()/1000);}); T1.start ();//To ensure that the thread T1 first obtains the object lock, where the main thread hangs for 1 seconds, and then executes the code behind the boot thread t2. Try {thread.sleep (1000);}  catch  (interruptedexception e)  {e.printstacktrace ();} If thread T2 enters Salary.method2 () after 4 seconds of startup, then the same object lock is requested. Otherwise, it is not the same object lock Thread t2 = new thread (new runnable ()  {@Overridepublic  void  run ()  {system.out.println (Thread.CurrentThread (). GetName () + " start at:" +system.currentTimemillis ()/1000);synchronized  (object 1)  {salary.method2 ();} System.out.println (Thread.CurrentThread (). GetName () + " end at:" +system.currenttimemillis ()/1000);}); T2.start ();}}

Operation Result:

Thread-0 Start at:1452077315

Thread-1 Start at:1452077316

Thread-0 has entered Method1 at:1452077320

Thread-1 has entered Method2 at:1452077320

Thread-1 End at:1452077320

Thread-0 End at:1452077320


synchronized (this): Holds the object lock for the current object instance of the Salary class

Concurrent Object Classes Salary:

public class Salary {private Object lock = new Object ();p ublic Salary (Object lock) {This.lock = lock;} public void Method1 () {synchronized (this) {try {thread.sleep ()} catch (Interruptedexception e) {//TODO Auto-generat Ed catch Blocke.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "have entered method1 at:" +system.currenttimemillis ()/1000);}} public void Method2 () {System.out.println (Thread.CurrentThread (). GetName () + "have entered method2 at:" + System.currenttimemillis ()/1000);}}


Concurrent Program Synchronizetest:

Public class synchronizetest {public static void main (String[] args)  { final object  Object 1 = new object ();final salary salary = new  Salary (object 1); Thread t1 = new thread (new runnable ()  {@Overridepublic  void run ()  {system.out.println (Thread.CurrentThread (). GetName () + " start at:" +system.currenttimemillis ()/ ); Salary.method1 (); System.out.println (Thread.CurrentThread (). GetName () + " end at:" +system.currenttimemillis ()/1000);}); T1.start ();//To ensure that the thread T1 first obtains the object lock, where the main thread hangs for 1 seconds, and then executes the code behind the boot thread t2. Try {thread.sleep (1000);}  catch  (interruptedexception e)  {e.printstacktrace ();} If thread T2 enters Salary.method2 () after 4 seconds of startup, then the same object lock is requested. Otherwise, it is not the same object lock Thread t2 = new thread (new runnable ()  {@Overridepublic  void  run ()  {system.out.println (Thread.CurrentThread (). GetName () + " start at:" +system.currentTimemillis ()/1000);synchronized  (Salary)  {salary.method2 (); System.out.println (Thread.CurrentThread (). GetName () + " end at:" +system.currenttimemillis ()/1000);}); T2.start ();}}

Operation Result:

Thread-0 Start at:1452077439

Thread-1 Start at:1452077440

Thread-0 has entered Method1 at:1452077444

Thread-0 End at:1452077444

Thread-1 has entered Method2 at:1452077444

Thread-1 End at:1452077444


V, synchronized (salary.class): hold salary.class object Lock

In the same vein as the test program.


To summarize, there may be a lot of variants of synchronized, but original aim, the analysis of whether multiple threads are mutually exclusive at synchronized, is essentially an analysis of whether the object lock held by synchronized is the same object lock. This is the key!

This article is from the "Bccat Technology History" blog, please be sure to keep this source http://bccat.blog.51cto.com/8845284/1732222

Java synchronized Keywords

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.