Java concurrent programming practice (1) java class lock and object lock

Source: Internet
Author: User

I recently read Java Concurrent in Practice (java Concurrent programming Practice) and found that I have a superficial understanding of java threads, locks, and other mechanisms, and I have not learned fully enough. I plan to use this book to comprehensively learn about the concurrent development of JDK and some thread-related theoretical knowledge, and fill in my own gaps. I can also communicate with you and understand what is incorrect, thank you for your correction. In the first blog, I will briefly introduce the concepts of class locks and Object locks, and the keywords synchronized.


Object lock:All java objects contain one mutex lock, which is automatically acquired and released by JVM. When the thread enters the synchronized method, it obtains the Lock of this object. Of course, if a thread has obtained the Lock of this object, the current thread will wait. The synchronized Method returns normally or terminates when an exception is thrown, the JVM Automatically releases the object lock. This also shows one benefit of locking with synchronized. When a method throws an exception, the lock can still be automatically released by JVM.

Class lock:Object locks are used to control synchronization between instance methods, and class locks are used to control synchronization between static methods (or static variable mutex. In fact, the class lock is only a conceptual thing, not actually exists. It is only used to help us understand the difference between the locking method and the static method. We all know that the java Class may have many objects, but there is only one Class object. That is to say, different instances of the Class share the Class Object of the Class. The Class object is actually only a java object, but it is a little special. Each java object has a mutex lock, and the static method of the Class requires the Class object. So the so-called Class lock is just the lock of the Class Object. There are several methods to obtain Class objects of a class. The simplest method is MyClass. Class.


Why is lock required? It must be because different threads have concurrent access to the shared object, and there is no need to lock the shared object without data sharing.

The following class is the method we use java's synchronized Method for control, which will be called in the thread next to us.

Package net.aty.lock.tar get; public class TargetMethod {// object lock: Form 1 public synchronized void objLockMethod1 () {System. out. println ("in... objLockMethod1 "); try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("out... objLockMethod1 ");} // object lock: Form 2 public void objLockMethod2 () {synchronized (this) {System. out. println ("in... objLockMethod2 "); try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("out... objLockMethod2 ") ;}}// class lock: Form 1 public static synchronized void classLock1 () {System. out. println ("classLock1 ------ in"); try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("classLock1 ------ out");} // class lock: Form 2 public void classLock2 () {synchronized (TargetMethod. class) {System. out. println ("classLock2 ------ in"); try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("classLock2 ------ out ");}}}

1. Let's take the first test first. This test is very simple. Note: If the thread does not share data, the lock will not work and there is no need to lock it.

package net.aty.lock.thread.first;import net.aty.lock.target.TargetMethod;public class DemoThread1 extends Thread{private TargetMethod target = null;public DemoThread1(TargetMethod target){this.target = target;}@Overridepublic void run(){target.objLockMethod1();}}

package net.aty.lock.thread.first;import net.aty.lock.target.TargetMethod;public class DemoThread2 extends Thread{private TargetMethod target = null;public DemoThread2(TargetMethod target){this.target = target;}@Overridepublic void run(){target.objLockMethod2();}}
Package net. aty. lock. thread. first; import net.aty.lock.tar get. targetMethod; public class Test {public static void main (String [] args) throws Exception {test2 ();} public static void test1 () throws Exception {TargetMethod target1 = new TargetMethod (); TargetMethod target2 = new TargetMethod (); // After thread 1 is run, sleep 500 msThread t1 = new DemoThread1 (target1 ); t1.start (); // after the main Thread is sleeping for MS, It is resumed and Thread 1 is still in sleep state. sleep (1, 100); System. out. println ("main thread runnig .... "); // Thread 2 starts to run Thread t2 = new DemoThread2 (target2); t2.start ();} public static void test2 () throws Exception {TargetMethod shared = new TargetMethod (); thread t1 = new DemoThread1 (shared); t1.start (); Thread. sleep (1, 100); System. out. println ("main thread runnig .... "); Thread t2 = new DemoThread2 (shared); t2.start ();}}
2. Test the second group to verify that the so-called "class lock" can indeed achieve the effect of Controlling Static Method synchronization.

package net.aty.lock.thread.second;import net.aty.lock.target.TargetMethod;public class DemoThread3 extends Thread{public DemoThread3(){}@Overridepublic void run(){TargetMethod.classLock1();}}

package net.aty.lock.thread.second;import net.aty.lock.target.TargetMethod;public class DemoThread4 extends Thread{private TargetMethod target = null;public DemoThread4(TargetMethod target){this.target = target;}@Overridepublic void run(){target.classLock2();}}

Package net. aty. lock. thread. second; import net.aty.lock.tar get. targetMethod; public class Test {public static void main (String [] args) throws Exception {// After thread 3 is run, sleep 500 msThread t1 = new DemoThread3 (); t1.start (); // The main Thread will resume execution after Ms of sleep. At this time, Thread 1 is still in sleep state. sleep (1, 100); System. out. println ("main thread runnig .... "); // Thread 4 starts to run Thread t2 = new DemoThread4 (new TargetMethod (); t2.start ();}}

The execution result is as follows: through analysis, we can know that the synchronized access between static methods is indeed implemented.

ClassLock1 ------ in
Main thread runnig ....
ClassLock1 ------ out
ClassLock2 ------ in
ClassLock2 ------ out

3. Finally, let's test the differences and relationships between Object locks and class locks. Thread 5 will access the synchronized instance method, and thread 6 will access the synchronized static method.

package net.aty.lock.thread.third;import net.aty.lock.target.TargetMethod;public class DemoThread5 extends Thread{private TargetMethod target = null;public DemoThread5(TargetMethod target){this.target = target;}@Overridepublic void run(){target.objLockMethod1();}}
package net.aty.lock.thread.third;import net.aty.lock.target.TargetMethod;public class DemoThread6 extends Thread{public DemoThread6(){}@Overridepublic void run(){TargetMethod.classLock1();}}
Package net. aty. lock. thread. third; import net.aty.lock.tar get. targetMethod; public class Test {public static void main (String [] args) throws Exception {test2 ();} public static void test1 () throws Exception {// Thread 5 starts to run Thread t1 = new DemoThread5 (new TargetMethod (); t1.start (); // The main Thread resumes execution after Ms of sleep, thread 1 is still in sleep state. sleep (1, 100); System. out. println ("main thread runnig .... "); // After thread 6 is run, sleep 500 msThread t2 = new DemoThread6 (); t2.start ();} public static void test2 () throws Exception {// Thread 6 starts to run Thread t2 = new DemoThread6 (); t2.start (); // resume execution after the main Thread is sleeping for ms, thread 1 is still in sleep state. sleep (1, 100); System. out. println ("main thread runnig .... "); // Thread 5 Thread t1 = new DemoThread5 (new TargetMethod (); t1.start ();}}

The execution result is as follows:

ClassLock1 ------ in
Main thread runnig ....
In... objLockMethod1
ClassLock1 ------ out
Out... objLockMethod1

It can be seen that the Class lock and the object lock are not the same thing. One is the lock of the Class object and the other is the lock of the Class instance. That is to say, when one thread accesses static synchronized, another thread is allowed to access the instance synchronized Method of the object. The opposite is true because the locks they need are different.



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.