search
HomeJavajavaTutorialLet's take a look at the 4 features of synchronized

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:
Lets take a look at the 4 features of synchronized
☹ 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

So, in the above program, when the thread enters the synchronization method method1, it obtains the object lock of Service1, but when executing method1, the synchronization method method2 is called. According to the normal In this case, when executing the synchronization method method2, you also need to obtain the object lock. However, according to the above lock release conditions, the object lock of method1 has not been released at this time, which will cause a deadlock and method2 cannot continue to be executed. However, judging from the execution results of the above code, method2 and method3 can be executed normally, which means that

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:


Lets take a look at the 4 features of synchronizedThis 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:
Lets take a look at the 4 features of synchronizedSince 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.

Uncomment

Integer.parseInt(“a”); in the Service4 class, and the execution result is as follows:

Lets take a look at the 4 features of synchronized
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:


Lets take a look at the 4 features of synchronizedLocking 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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

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...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

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...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

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...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

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

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

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 default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

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

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

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