Java thread synchronization: synchronized detailed

Source: Internet
Author: User

The Java language keyword that, when used to decorate a method or a block of code, guarantees that at most one thread executes the code at the same time.

One, only one thread can be executed within a time when two concurrent threads access the synchronized (this) synchronous code block in the same object . (If multiple threads call the same thread, only one thread will be executed). the other thread must wait for the current thread to finish executing the block before it can execute the code block .

Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized (this) in the object Synchronize code blocks.

Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, the other thread synchronizes the code block for all other synchronized (this) in the object. Access will be blocked .

The third example also applies to other synchronous blocks of code. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.

The above rules apply to other object locks as well.

To illustrate:
First, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

 Packageths; Public classThread1ImplementsRunnable { Public voidrun () {synchronized( This) {                  for(inti = 0; I < 5; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "Synchronized loop" +i); }            }       }        Public Static voidMain (string[] args) {Thread1 T1=NewThread1 (); Thread Ta=NewThread (T1, "A"); Thread TB=NewThread (T1, "B");            Ta.start ();       Tb.start (); } }

Results:

 A synchronized  loop 0 A  synchronized  loop 1 A  syn  Chronized  loop 2 A  synchronized  loop 3 A  synchronized  loop 4 b  synchronized  loop 0 B synchronized  loop 1 B  synchronized  loop 2 B  synchroniz  Ed  loop 3 B  synchronized  Loop 4 

Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.

 Packageths; Public classThread2 { Public voidm4t1 () {synchronized( This) {                 inti = 5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ " : " +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}} }        Public voidm4t2 () {inti = 5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ " : " +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}}  Public Static voidMain (string[] args) {FinalThread2 myt2 =NewThread2 (); Thread T1=NewThread (NewRunnable () { Public voidRun () {myt2.m4t1 (); }}, "T1"  ); Thread T2=NewThread (NewRunnable () { Public voidRun () {myt2.m4t2 (); }}, "T2"  );            T1.start ();       T2.start (); } }

Results:

T1:4       4       33       2       21                      1       00       

Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, other threads will block access to all other synchronized (this) synchronization blocks in object.

To modify the Thread2.m4t2 () method:

 public  void   M4t2 () { synchronized  (this  ) { int  I                 = 5;  while  (i--> 0 + ":" + i);  try   {Thread.Sleep (500 catch   (Interruptedexception IE) { }                 }            }     }

Results:

   T1:4       3       21       0       43                      2       10       

The third example also applies to other synchronous blocks of code. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.

Modify the Thread2.m4t2 () method as follows:

public void m4t2 () {            int i = 5;                while (i--> 0) {                 + ":" + i);                  Try {                      Thread.Sleep (+);                  Catch (Interruptedexception IE) {                 }        }}

Results:

  T1:4       3       21       0       43                      2       10       

The above rules apply to other object locks as well:

 Packageths;
Public classThread3 {classInner {Private voidm4t1 () {inti = 5; while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ": inner.m4t1 () =" +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}} Private voidm4t2 () {inti = 5; while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ": inner.m4t2 () =" +i); Try{Thread.Sleep (500); } Catch(Interruptedexception IE) {}}} } Private voidm4t1 (Inner Inner) {synchronized(inner) {//Using object Locksinner.m4t1 (); } Private voidm4t2 (Inner Inner) {inner.m4t2 (); } Public Static voidMain (string[] args) {FinalThread3 MYT3 =NewThread3 (); FinalInner Inner = myt3.NewInner (); Thread T1=NewThread (NewRunnable () { Public voidRun () {myt3.m4t1 (inner);}}, "T1"); Thread T2=NewThread (NewRunnable () { Public voidRun () {myt3.m4t2 (inner);}}, "T2");    T1.start (); T2.start (); } }

Results:

Although thread T1 obtains an object lock on inner, the thread T2 accesses the non-synchronized part of the same inner. So two threads do not interfere with each other .

  T1:INNER.M4T1 () =4       t2:Inner.m4t2 () =4       t1:Inner.m4t1 ()=3       t2:Inner.m4t2 ()=3        t1:Inner.m4t1 ()=2       t2:Inner.m4t2 () =2       t1:Inner.m4t1 ()=1       T2 : Inner.m4t2 ()=1       t1:Inner.m4t1 () =0       t2:Inner.m4t2 ()=0

Now add synchronized in front of Inner.m4t2 ():

Private synchronized void m4t2 () {            int i = 5;              while (i--> 0) {                 + ": inner.m4t2 () =" + i);                  Try {                      Thread.Sleep (+);                  Catch (Interruptedexception IE) {                 }        }}

Results:

Although thread T1 and T2 access two unrelated parts of the same inner object, inner's access to T2 () is blocked because T1 first acquired an object lock on Inner.m4t2, because M4t2 () is a synchronous method in inner.

T1:INNER.M4T1 () =4       t1:Inner.m4t1 () =3       t1:Inner.m4t1 () =2       t1:Inner.m4t1 () =1       t1:Inner.m4t1 () =0       T2:Inner.m4t2 () =4       t2:Inner.m4t2 () =3       t2:Inner.m4t2 () =2       t2:Inner.m4t2 () =1       t2:Inner.m4t2 () =0

Java thread synchronization: synchronized detailed (GO)

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.