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!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software