Java understanding of the use of synchronized keywords in different locations

Source: Internet
Author: User

The Synchronized keyword in Java

Can be used to modify the synchronization method:

Like this synchronized void F () {/*body*/}

You can also modify a synchronous statement block:

Like this synchronized (object) {/*body*/}.

The modified synchronization method can also be divided into modified static method and instance method.

Where the modified synchronous statement block can also be divided into modified instance variables, object reference objects reference, class literal constants.

When synchronized is acting on a method, the object instance (this) is locked;

So synchronized void F () {/*body*/} and void F (synchronized (this) {/*body*/}) are equivalent.

When the function is locked in the static method is the object corresponding class instance, because the class data exists perpetual band, so the static method lock is equivalent to a global lock of the class;

When synchronized acts on an object instance, the corresponding code block is locked.

In the Hotspot JVM implementation, the lock has a special name: Object Monitor.


Synchronized (Class)
Synchronized (This)
-> threads each get monitor, there is no wait.

Threads get the class and this separately, and do not cause an example of waiting:

Package Com.hyy.test;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public Class SyncTest02 implements Runnable {private static Boolean flag = True;private void TestSync1 () {synchronized (this) {fo R (int i = 0; i < i++) {System.out.println ("Testsyncobject:" + i);}}} private void TestSync2 () {synchronized (Synctest02.class) {for (int i = 0; i <; i++) {System.out.println ("TESTSYNCC Lass: "+ i);}}} @Overridepublic void Run () {//TODO auto-generated method stubif (flag) {flag = False;testsync1 ();} else {flag = True;test Sync2 ();}} public static void Main (string[] args) {Executorservice exec = Executors.newfixedthreadpool (2); SyncTest02 sy1 = new SyncTest02 (); SyncTest02 sy2 = new SyncTest02 (); Exec.execute (sy1); Exec.execute (sy2); Exec.shutdown ();}}


Synchronized (This)
Synchronized (This)
-> If a different thread monitors the same instance object, it waits if a different instance does not wait.

examples of different threads monitoring the same instance object :

Package Com.hyy.test;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public Class Synctest {public static void main (string[] args) {Executorservice es = Executors.newfixedthreadpool (2); MyCount mc = new MyCount (); MyThread MT1 = new MyThread (MC, "Thread 1"); MyThread mt2 = new MyThread (MC, "Thread 2"); Es.execute (MT1); Es.execute (MT2); Es.shutdown ();}} Class MyThread extends Thread {MyCount count; String Threadname;public MyThread (MyCount count, String threadname) {//TODO auto-generated constructor Stubthis.count = C Ount;this.threadname = ThreadName;} @Overridepublic void Run () {//TODO auto-generated method stubfor (int i = 0; i < ten; i++) {count.addone (threadname); tr y {sleep (100L);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} Class MyCount {int i;public void AddOne (String threadname) {synchronized (this) {i++; System.out.println (ThreadName + ":" + i);}}}

Output to

Thread 1:1thread 2:2thread 1:3thread 2:4thread 2:5thread 1:6thread 2:7thread 1:8thread 1:9thread 2:10thread 1:11thread 2:1 2thread 2:13thread 1:14thread 1:15thread 2:16thread 1:17thread 2:18thread 1:19thread 2:20

From the output, there is a wait between the threads


Examples of different thread monitoring of different instance objects:

Package Com.hyy.test;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public Class Synctest {public static void main (string[] args) {Executorservice es = Executors.newfixedthreadpool (2); MyCount mc = new MyCount ("Countone"); MyCount MC2 = new MyCount ("Counttwo"); MyThread MT1 = new MyThread (MC, "Thread 1"); MyThread mt2 = new MyThread (MC2, "Thread 2"); Es.execute (MT1); Es.execute (MT2); Es.shutdown ();}} Class MyThread extends Thread {MyCount count; String Threadname;public MyThread (MyCount count, String threadname) {//TODO auto-generated constructor Stubthis.count = C Ount;this.threadname = ThreadName;} @Overridepublic void Run () {//TODO auto-generated method stubfor (int i = 0; i < ten; i++) {count.addone (threadname); tr y {sleep (100L);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} Class MyCount {int i; String Countname;public MyCount (string countname) {//TODO auto-generated constructor stubthis.countname = countname;}public void AddOne (String threadname) {synchronized (this) {i++; System.out.println (ThreadName + "&&" +countname+ ":" + i);}}}

Output to

Thread 2&&counttwo:1thread 1&&countone:1thread 2&&counttwo:2thread 1&&countONE : 2thread 2&&counttwo:3thread 1&&countone:3thread 2&&counttwo:4thread 1&&countONE : 4thread 1&&countone:5thread 2&&counttwo:5thread 2&&counttwo:6thread 1&&countONE : 6thread 2&&counttwo:7thread 1&&countone:7thread 1&&countone:8thread 2&&countTWO : 8thread 2&&counttwo:9thread 1&&countone:9thread 1&&countone:10thread 2&&countTWO : 10

From the output, there is no waiting between threads.



Synchronized (Class)
Synchronized (Class)
-> If different threads monitor the same instance or different instance objects, they will wait.

Examples of different thread monitoring of different instance objects:

Package Com.hyy.test;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public Class SyncTest02 implements Runnable {private static Boolean flag = True;private void TestSync1 () {synchronized (SyncTest0 2.class) {for (int i = 0; i < i++) {System.out.println ("Testsyncobject:" + i);}}} private void TestSync2 () {synchronized (Synctest02.class) {for (int i = 0; i <; i++) {System.out.println ("TESTSYNCC Lass: "+ i);}}} @Overridepublic void Run () {//TODO auto-generated method stubif (flag) {flag = False;testsync1 ();} else {flag = True;test Sync2 ();}} public static void Main (string[] args) {Executorservice exec = Executors.newfixedthreadpool (2); SyncTest02 sy1 = new SyncTest02 (); SyncTest02 sy2 = new SyncTest02 (); Exec.execute (sy1); Exec.execute (sy2); Exec.shutdown ();}}



Java understanding of the use of synchronized keywords in different locations

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.