The lock is automatically released after wait is executed
- When wait is in the lock, the lock will be released after the wait is executed
- 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.
notify execution does not release the lock
- 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
- When the thread is in the wait state, an InterruptedException will occur when the interrupt method is executed.
Several conditions for releasing the lock
- When the synchronized code block is executed, the lock is released
- The execution of the synchronized code block encounters an exception, causing the thread to terminate and release the lock
- Execute a synchronized block of code