Let's take a look at the 4 features of synchronized
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(); } }
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(); } } }
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(); } }
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.
