线程同步锁中为什么锁对象和wait()或notify()的对象要一致?
package com.dtz.ThreadAndGui.day25.Thread;
import com.dtz.Thread.day24.syn.Demo1_synchronized;
public class Demo1_Notify {
public static void main(String[] args) {
final Demo d = new Demo();
new Thread(){
@Override
public void run() {
while(true) {
try {
d.print1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
new Thread(){
@Override
public void run() {
while(true) {
try {
d.print2();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}
class Demo {
private int flag = 1;
public void print1() throws InterruptedException {
synchronized (this) { //这里是Demo.class的话,下面的wait()和notify()会抛异常
if (flag != 1) {
this.wait();
}
System.out.print("a");
System.out.print("a");
System.out.print("a");
System.out.println();
flag = 2;
this.notify();
}
}
public void print2() throws InterruptedException {
synchronized (this) {
if (flag != 2) {
this.wait();
}
System.out.print("b");
System.out.print("b");
System.out.print("b");
System.out.print("b");
System.out.print("b");
System.out.println();
flag = 1;
this.notify();
}
}
}