证明 wait 只释放当前锁
/**
* 描述: 证明wait只释放当前的那把锁
*/
public class WaitNotifyReleaseOwnMonitor {
private static volatile Object resourceA = new Object();
private static volatile Object resourceB = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
System.out.println("Thread1 got resourceA lock.");
synchronized (resourceB) {
System.out.println("Thread1 got resourceB lock.");
try {
System.out.println("Thread1 releases resourceA lock.");
//将 A 锁释放,那么其他线程将可以获得这把锁的使用权
resourceA.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//获取 A 锁,由于 thread1 已经释放了 A 锁,所以可以成功取到
synchronized (resourceA) {
System.out.println("Thread2 got resourceA lock.");
System.out.println("Thread2 tries to resourceB lock.");
//这里无法获取 resourceB 锁,因为在 thread1 中并没有释放 B 锁,只释放了 A 锁
synchronized (resourceB) {
System.out.println("Thread2 got resourceB lock.");
}
}
}
});
thread1.start();
thread2.start();
}
}
运行结果
Thread1 got resourceA lock.
Thread1 got resourceB lock.
Thread1 releases resourceA lock.
Thread2 got resourceA lock.
Thread2 tries to resourceB lock.