(多线程问题)本人小白,刚学Java多线程,遇到同步锁释放问题,下面直接贴代码
问题1:我预期是打印出 1,2,3,4,5 结果在3之后死锁了,
为什么执行到了resourceA.notify(); 而不会唤醒之前的 wait(),
问题2:我尝试把synchronized (resourceB) ,拿出去和synchronized (resourceA)同级,
不执行 resourceA.notify(); 也会唤醒resourceA.wait(),成功输出 4 和 5
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("1");
synchronized (resourceB) {
System.out.println("2");
try {
resourceA.wait();
System.out.println("4");
// System.out.println("唤醒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();
}
synchronized (resourceA) {
System.out.println("3");
resourceA.notify();
synchronized (resourceB) {
System.out.println("5");
}
}
}
});
thread1.start();
thread2.start();
}
}