Synchronized Sync Lock Details

Source: Internet
Author: User

1. Synchronized method: Declare the Synchronized method by adding the Synchronized keyword to the method declaration. Such as:
Public synchronized void Accessval (int newval);
The Synchronized method Controls access to class member variables: Each class instance corresponds to a lock, and each synchronized method must obtain a lock on the class instance that invokes the method to

execution, otherwise the owning thread is blocked, and once the method executes, the lock is exclusive until the lock is released when the method returns, and then the blocked thread can obtain the lock and re-enter the executable

State. This mechanism ensures that at the same time for each class instance, at most one of its member functions declared as synchronized is in an executable state (because at most only

A lock that can obtain the corresponding instance of the class, thus effectively avoiding access violations of class member variables (as long as all methods that may access the class member variable are declared as synchronized)


In Java, not only class instances, each class also corresponds to a lock, so we can also declare the static member function of the class as synchronized to control its static

Access to the operator variable.
The flaw of the Synchronized method: Declaring a large method as synchronized will greatly affect efficiency, typically if the method run () of the thread class is declared as

Synchronized, because it has been running throughout the lifetime of the thread, will cause its call to any synchronized method in this class to never succeed. Of course we can.

To resolve the problem by putting the code that accesses the class member variable into a specialized method, declaring it as synchronized, and calling it in the main method, but Java gives us

A better solution, that is the synchronized block.
2. Synchronized BLOCK: Declare the synchronized block by synchronized keyword. The syntax is as follows:
Synchronized (SyncObject) {
Code that allows access control
}
The synchronized block is a block of code in which the code must obtain the object SyncObject (as previously described, can be class instances or classes) of the lock can be executed, the specific machine

System as described above. Because it can be arbitrary code block, and can arbitrarily specify the locked object, it is more flexible.

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.

package ths;

public class Thread1 implements Runnable {
public void Run () {
Synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println (Thread.CurrentThread (). GetName () + "synchronized loop" + i);
}
}
}
public static void Main (string[] args) {
Thread1 T1 = new Thread1 ();
Thread ta = new Thread (T1, "A");
Thread TB = new Thread (T1, "B");
Ta.start ();
Tb.start ();
}
}

Results:
A Synchronized Loop 0
A Synchronized Loop 1
A Synchronized Loop 2
A Synchronized Loop 3
A Synchronized Loop 4
B Synchronized Loop 0
B Synchronized Loop 1
B Synchronized Loop 2
B Synchronized 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.

package ths;

public class Thread2 {
public void M4t1 () {
Synchronized (this) {
int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + i);
try {
Thread.Sleep (500);
} catch (Interruptedexception IE) {
}
}
}
}
public void M4t2 () {
int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + i);
try {
Thread.Sleep (500);
} catch (Interruptedexception IE) {
}
}
}
public static void Main (string[] args) {
Final Thread2 myt2 = new Thread2 ();
thread T1 = new Thread (new Runnable () {public void run () {myt2.m4t1 (); }}, "T1");
Thread t2 = new Thread (new Runnable () {public void run () {myt2.m4t2 (); }}, "T2");
T1.start ();
T2.start ();
}
}

Results:
T1:4
T2:4
T1:3
T2:3
T1:2
T2:2
T1:1
T2:1
t1:0
t2:0

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) {
System.out.println (Thread.CurrentThread (). GetName () + ":" + i);
try {
Thread.Sleep (500);
} catch (Interruptedexception IE) {
}
}
}

}

Results:

T1:4
T1:3
T1:2
T1:1
t1:0
T2:4
T2:3
T2:2
T2:1
t2:0

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 synchronized void M4t2 () { 
           int i = 5; 
          while (i--> 0) { 
               System.out.println (Thread.CurrentThread (). GetName () + ":" + i);  
                try { 
                     Thread.Sleep ($);  
                catch (interruptedexception IE) { 
              } 
          } 
    }

Results:
T1:4
T1:3
T1:2
T1:1
t1:0
T2:4
T2:3
T2:2
T2:1
t2:0

The above rules apply to other object locks as well:

package ths;

public class Thread3 {
Class Inner {
private void M4t1 () {
int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ": inner.m4t1 () =" + i);
try {
Thread.Sleep (500);
} catch (Interruptedexception IE) {
}
}
}
private void M4t2 () {
int i = 5;
while (i--> 0) {
System.out.println (Thread.CurrentThread (). GetName () + ": inner.m4t2 () =" + i);
try {
Thread.Sleep (500);
} catch (Interruptedexception IE) {
}
}
}
}
private void M4t1 (Inner Inner) {
Synchronized (inner) {//Use object lock
Inner.m4t1 ();
}

private void M4t2 (Inner Inner) {
Inner.m4t2 ();
}

public static void Main (string[] args) {
Final Thread3 myt3 = new Thread3 ();
Final Inner Inner = Myt3.new Inner ();
thread T1 = new Thread (new Runnable () {public void run () {myt3.m4t1 (inner);}}, "T1");
Thread t2 = new Thread (new Runnable () {public void run () {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) { 
                System.out.println (Thread.CurrentThread (). GetName () + ": 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

Synchronized Sync Lock Details

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.