1. synchronized lock reentrancy
1.1 Introduction
The keyword synchronized has the function of lock reentrancy, that is, when using synchronized, when a thread obtains an object lock, it can obtain the object lock again when it requests the object lock again. This shows that when calling other synchronized methods/blocks of this class within a synchronized method/block, the lock can always be obtained.
For example:
public class Service1 { public synchronized void method1(){ System.out.println("method1"); method2(); } public synchronized void method2(){ System.out.println("method2"); method3(); } public synchronized void method3(){ System.out.println("method3"); } }
public class MyThread extends Thread { @Override public void run(){ Service1 service1 = new Service1(); service1.method1(); } public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); } }
The running result is as follows:
☹ When I saw this result, I was confused, why? Has it been proven that the reentrant lock is?
➤ The concept of "reentrant lock" is that you can acquire your own internal lock again. For example, a thread acquires the lock of an object. At this time, the object lock has not been released. When it wants to acquire it again, It is still possible to acquire the lock of this object. If the lock cannot be reentrant, a deadlock will occur.
➤ The biggest role of "reentrant lock" is toavoid deadlock
##1.2 Analysis
us Know that in the program, the lock on the synchronization monitor cannot be explicitly released, but the lock will be released in the following situations:① Released when the synchronization method and code block of the current thread end execution
② Released when the current thread encounters break or return when the synchronized method or synchronized code block terminates the code block or method
③ Released when an unhandled error or exception occurs causing an abnormal end
④ The program executes the synchronization object wait method, the current thread pauses and releases the lock
When calling other Synchronized modified methods or code blocks of this class inside a Synchronized modified method or code block, it is You can always get the of the lock.
1.3 Parent-child inheritability
Reentrant locks are supported in the environment of parent-child class inheritance. The sample code is as follows:public class Service2 { public int i = 10; public synchronized void mainMethod(){ i--; System.out.println("main print i="+i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
public class Service3 extends Service2 { public synchronized void subMethod(){ try{ while (i>0){ i--; System.out.println("sub print i= "+i); Thread.sleep(100); this.mainMethod(); } }catch (InterruptedException e){ e.printStackTrace(); } } }
public class MyThread extends Thread { @Override public void run(){ Service3 service3 = new Service3(); service3.subMethod(); } public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); } }The running results are as follows:
This program shows that when there is an inheritance relationship between parent and child classes, the subclass can completely call the synchronization method of the parent class through "reentrant lock".
2. When an exception occurs, the lock is automatically released
When an exception occurs in the code executed by a thread, the lock it holds is automatically released freed.The verification code is as follows:
public class Service4 { public synchronized void testMethod(){ if(Thread.currentThread().getName().equals("a")){ System.out.println("ThreadName= "+Thread.currentThread().getName()+" run beginTime="+System.currentTimeMillis()); int i=1; while (i == 1){ if((""+Math.random()).substring(0,8).equals("0.123456")){ System.out.println("ThreadName= "+Thread.currentThread().getName()+" run exceptionTime="+System.currentTimeMillis()); //Integer.parseInt("a"); } } }else{ System.out.println("Thread B run time= "+System.currentTimeMillis()); } } }
public class ThreadA extends Thread{ private Service4 service4; public ThreadA(Service4 service4){ this.service4 = service4; } @Override public void run(){ service4.testMethod(); } }
public class ThreadB extends Thread{ private Service4 service4; public ThreadB(Service4 service4){ this.service4 = service4; } @Override public void run(){ service4.testMethod(); } }
public class Main { public static void main(String[] args) { try { Service4 service4 = new Service4(); ThreadA a = new ThreadA(service4); a.setName("a"); a.start(); Thread.sleep(500); ThreadB b = new ThreadB(service4); b.setName("b"); b.start(); } catch (InterruptedException e) { e.printStackTrace(); } } }Note that
Integer.parseInt(“a”);in the Service4 class is in an annotated state at this time, and the running results are as follows:
Since there is no error in thread a, while(true), thread a is in an infinite loop state at this time, the lock is always occupied by a, thread b cannot obtain the lock, that is, thread b cannot be executed.
Integer.parseInt(“a”); in the Service4 class, and the execution result is as follows:
When When an error occurs in thread a, thread b obtains the lock and executes it. It can be seen that when an exception occurs in the method, the lock is automatically released.
3. Use any object as a monitor
#java supports the function of synchronizing "any object" as an "object monitor" . Most of these "arbitrary objects" are instance variables and method parameters, and the format is synchronized (not this object x) synchronized code block.The sample code is as follows:
public class StringLock { private String lock = "lock"; public void method(){ synchronized (lock){ try { System.out.println("当前线程: "+Thread.currentThread().getName() + "开始"); Thread.sleep(1000); System.out.println("当前线程: "+Thread.currentThread().getName() + "结束"); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { final StringLock stringLock = new StringLock(); new Thread(new Runnable() { @Override public void run() { stringLock.method(); } },"t1").start(); new Thread(new Runnable() { @Override public void run() { stringLock.method(); } },"t2").start(); } }The running results are as follows:
Locking non-this objects has certain advantages: if there are many synchronized methods in a class, although Synchronization can be achieved, but it will be blocked, so operating efficiency is affected; but if a synchronized code block is used to lock a non-this object, the program and synchronization method in the synchronized (non-this) code block are asynchronous, and other lock this synchronization methods are not allowed. Fighting for this lock can greatly improve operating efficiency.
4. Synchronization does not have inheritance
#The synchronization method of the parent class will not work if it is rewritten in the subclass without adding the synchronization keyword. Synchronous, so you have to add the synchronized keyword to the method of the subclass.
Recommended learning: Java video tutorial
The above is the detailed content of Let's take a look at the 4 features of synchronized. For more information, please follow other related articles on the PHP Chinese website!