Synchronized keyword Understanding in Java

Source: Internet
Author: User

Good memory is better than bad writing ~ ~

并发编程中synchronized关键字的地位很重要,很多人都称它为重量级锁。利用synchronized实现同步的基础:Java中每一个对象都可以作为锁。具体表现为以下三种形式。

(1) for the normal synchronization method, the lock is the current instance object.

(2) for the static synchronization method, the lock is the class object of the current classes.

(3) for a synchronous method block, the lock is an object configured in synchronized brackets.

One, common synchronization method

Use the Synchronized keyword to decorate an ordinary method that locks the object of the current instance. When synchronized locks the 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.

Experiment One

Class synch{public synchronized  void Test1 () {System.out.println ("test1 start"), try {thread.sleep (+);} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Test1 End");} Public synchronized void Test2 () {System.out.println ("test2 start"), try {thread.sleep (+);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Test2 End");}} public class Synctest extends synch{public   static void Main (String args[]) {   Synch s=new Synch ();   Thread T1=new Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubs.test1 ();}      );   thread t2=new Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubs.test2 ();});   T1.start ();   T2.start ();   }}

Experimental results:

Analyzing the above code, there are two common synchronization methods Test1 and Test2 in class synch. The class is implemented in the main function, and two thread threads are defined, and the method of the class synch is called separately in the Run method. Synchronized implements a common synchronization method that locks the current instance object, which is the Synch class object. Because two threads are synchronous methods in the same object that is called, only one thread frees the object's lock and another thread can call it.

Experiment Two

Class sync{public synchronized void Test (String threadname) {System.out.println (threadname+ "start"); try {thread.sleep ( 1000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (threadname+ "End");}} Class MyThread extends Thread{public int i;public MyThread (int i) {this.i=i;} Sync s=new sync ();p ublic void Run () {//sync sync=new Sync (); S.test ("Thread" +i);}} public class Syntest {public    static void Main (String args[]) {for    (int i=0;i<3;i++) {Thread thread=new MyThread (i); Thread.Start ();}}    }

Experimental results:

The code above, each thread is new to a sync class object, that is, the creation of three sync objects, because it is not the same object, so you can multi-threaded simultaneous running synchronized method.

Second, static synchronization method

For a static synchronization method, the lock is the class object of the current classes, so the static Synchronized method is also equivalent to a global lock, which is equivalent to locking the code snippet. Only one thread ends and another thread gets a lock.

Experiment Three

Class Synch{public static synchronized  void Test1 () {System.out.println ("test1 start"); try {thread.sleep (1000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Test1 End");} public static synchronized  void Test2 () {System.out.println ("test2 start"), try {thread.sleep (+);} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println ("Test2 End");}} public class Synctest extends synch{public   static void Main (String args[]) {   Synch s1=new Synch ();   Synch s2=new Synch ();   Thread T1=new Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubs1.test1 ();}      );   thread t2=new Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubs2.test2 ();});   T1.start ();   T2.start ();   }}

Experimental results:

Three, synchronous method block

This section is better understood, locking the objects that are configured in the synchronized brackets.

Experiment Four

public class ThreadTest implements runnable{@Overridepublic void Run () {//TODO auto-generated method stubsynchronized (th IS) {for  (int i = 0; i < 5; i++) {                    System.out.println (Thread.CurrentThread (). GetName () + "synchronized loop" + i);}}}  public static void Main (string[] args) {          threadtest t1 = new ThreadTest ();          Thread ta = new Thread (T1, "A");          Thread TB = new Thread (T1, "B");          Ta.start ();          Tb.start ();     } }

Operation Result:

The code above, the synchronized code block is configured in parentheses in the object is this, the same object, so that only one thread accesses the code block after the end, release the lock, another thread can access the code block.

It is important to note that other threads can access the non-synchronized (this) synchronization code. The following code

Experiment Five

Class Mythread1{public void Test1 () {    synchronized (this) {    System.out.println ("Synchronous code block-test1 start");    try {thread.sleep;} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}    SYSTEM.OUT.PRINTLN ("Synchronous code block-test1 end");    }    }    public void Test2 () {    try {thread.sleep ($)} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.pri Ntstacktrace ();}    SYSTEM.OUT.PRINTLN ("Non-synchronous code block-test2");}    } public class ThreadTest1 {public static void main (String args[]) {    MyThread1 t=new MyThread1 ();    Thread T1=new Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubt.test1 ();}        );    thread t2=new Thread (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubt.test2 ();}        });    T1.start ();    T2.start ();}}

Operation Result:

The synchronized brackets are configured with this, but the code is locked, the same object, only one thread can access the code block, release the lock, other threads can access, but does not affect other threads to access the non-synchronous code block.

Synchronous code block, implementation of synchronous method ~ ~ Simple Understanding

For synchronous code blocks is implemented using the Monitorenter, monitorexit directives. Each object has a monitor lock, which is locked when monitor is occupied.

The thread executes the monitorenter instruction to attempt to gain ownership of the monitor.

    • If the monitor has an entry number of 0, the thread goes into monitor and sets the entry number to 1
    • If the thread already occupies the monitor, re-enter, enter the number to +1
    • If another thread consumes monitor, the thread goes into a blocking state, knowing that the entry number is 0

For the synchronous method, the acc_synchronized identifier is more in the constant pool, the access flag of the identifier is checked first when the method is called, and if set, the process obtains the monitor first, the method body is executed after the method is executed, and the monitor is released after execution.

Tidy up, should not forget ~ ~ Reference http://www.cnblogs.com/QQParadise/articles/5059824.html

Synchronized keyword Understanding 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.