The lock is automatically released after wait is executed, and the lock is not released when notify is executed

The lock is automatically released after wait is executed

  1. When wait is in the lock, the lock will be released after the wait is executed
  2. When notify is in the lock, wait is awakened when notify is executed, but the thread does not release the lock

The test code is as follows:

package com.chapter03;

class Service02 {
    
    
    public void testMethod(Object lock) {
    
    
        try {
    
    
            synchronized (lock) {
    
    
                System.out.println("begin wait");
                lock.wait();
                System.out.println("end wait");
            }
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }

}

class ThreadA extends Thread {
    
    
    private Object lock;

    public ThreadA(Object lock) {
    
    
        this.lock = lock;
    }

    @Override
    public void run() {
    
    
        Service02 service02 = new Service02();
        service02.testMethod(lock);
    }
}

class ThreadB extends Thread {
    
    
    private Object lock;

    public ThreadB(Object lock) {
    
    
        this.lock = lock;
    }

    @Override
    public void run() {
    
    
        Service02 service02 = new Service02();
        service02.testMethod(lock);
    }
}

public class StudyThreads02释放锁与不释放锁 {
    
    
    public static void main(String[] args) {
    
    
        Object lock = new Object();
        ThreadA threadA = new ThreadA(lock);
        ThreadB threadB = new ThreadB(lock);
        threadA.start();
        threadB.start();
    }
}

Execution result: The lock is released after the wait is executed, and thread B gets the lock and starts executing until the wait continues to wait.

insert image description here

notify execution does not release the lock

  1. Wake up the corresponding thread after executing notify, but the thread will not release the lock until the execution is complete.

Execute interrupt in wait state

  1. When the thread is in the wait state, an InterruptedException will occur when the interrupt method is executed.

Several conditions for releasing the lock

  1. When the synchronized code block is executed, the lock is released
  2. The execution of the synchronized code block encounters an exception, causing the thread to terminate and release the lock
  3. Execute a synchronized block of code

Guess you like

Origin blog.csdn.net/weixin_43960044/article/details/121053662