wait() 和notify()
1、必须同时出现
2、必须在同步环境下
3、子线程和子线程通信
public class PrintChar {
private boolean flag;
public void printA() {
synchronized (this) {
while(true) {
if(flag) {
try {
this.wait();//如果flag是false则当前线程被阻塞
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" A");
flag=true;
this.notify();
}
}
}
public void printB() {
synchronized (this) {
while(true) {
if(!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" B");
flag=false;
this.notify();
}
}
}
}