wait:告诉当前线程放弃监视器并进入睡眠状态,直到其它线程进入同一监视器并调用notify为止。
notify:唤醒同一对象监视器中调用wait的第一个线程。类似排队买票,一个人买完之后,后面的人可以继续买。
notifyAll:唤醒同一对象监视器中调用wait的所有线程,具有最高优先级的线程
首先被唤醒并执行。
多线程中,suspend方法、resume方法和stop方法不推荐使用。
public class ThreadCommunation {
public static void main(String args[]) {
Person person = new Person();
new Thread(new Producer(person)).start();
new Thread(new Consumer(person)).start();
}
}
class Producer implements Runnable {
private Person mPerson;
public Producer(Person persion) {
mPerson = persion;
}
public void run() {
int i = 0;
while(true) {
if (i == 0) {
mPerson.set("男", "张三");
} else {
mPerson.set("女", "李四");
}
i = (i + 1) % 2;
}
}
}
class Consumer implements Runnable {
private Person mPerson;
public Consumer(Person persion) {
mPerson = persion;
}
public void run() {
// TODO Auto-generated method stub
while(true) {
mPerson.get();
}
}
}
class Person {
private String sex = "男";
private String name = "张三";
boolean bFull = false;
public synchronized void get() {
if(!bFull) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(this.name +"----->"+this.sex);
bFull = false;
notify();
}
public synchronized void set(String sex, String name) {
if(bFull) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name = name;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.sex = sex;
bFull = true;
notify();
}
}