Home > Java > javaTutorial > body text

Let's take a look at the 4 features of synchronized

青灯夜游
Release: 2020-07-07 16:18:43
forward
2987 people have browsed it

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");
    }

}
Copy after login
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();
    }
}
Copy after login

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();
        }
    }
}
Copy after login
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();
        }
    }
}
Copy after login
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();
    }
}
Copy after login

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());
        }
    }
}
Copy after login
public class ThreadA extends Thread{

    private Service4 service4;

    public ThreadA(Service4 service4){
        this.service4 = service4;
    }

    @Override
    public void run(){
        service4.testMethod();
    }
}
Copy after login
public class ThreadB extends Thread{

    private Service4 service4;

    public ThreadB(Service4 service4){
        this.service4 = service4;
    }

    @Override
    public void run(){
        service4.testMethod();
    }
}
Copy after login
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();
        }
    }
}
Copy after login

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();
    }
}
Copy after login
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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template