class Person {
private String name;
private String sex;
private Boolean isEmpty = Boolean.TRUE; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public Boolean getIsEmpty() {
return isEmpty;
} public void setIsEmpty(Boolean isEmpty) {
this.isEmpty = isEmpty;
}
}class Producer implements Runnable { private Person p; public Producer(Person p) {
this.p = p;
} public void run() {
for (int i = 0; i < 100; i++) {
synchronized (p) { if (!p.getIsEmpty().equals(Boolean.TRUE)) {
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} if (i % 2 == 0) {
p.setName("春哥");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
p.setSex("男");
} else {
p.setName("著姐");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
p.setSex("女");
}
p.setIsEmpty(Boolean.FALSE);
p.notify();
}
}
}
}class Consumer implements Runnable {
private Person p; public Consumer(Person p) {
this.p = p;
} public void run() {
for (int i = 0; i < 100; i++) {
synchronized (p) {
if (!p.getIsEmpty().equals(Boolean.FALSE)) {
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = p.getName();
String sex = p.getSex();
System.out.println(name + "--->" + sex);
}
p.setIsEmpty(Boolean.TRUE);
p.notify();
}
}
}public class CopyOfProducer_ConsumerDemo {
public static void main(String[] args) {
Person p = new Person();
new Thread(new Producer(p), "生产者").start();
new Thread(new Consumer(p), "消费者").start(); }
}

解决方案 »

  1.   

    synchronized 修饰的是run方法,然后里面用wait 和 notif 方法
      

  2.   

    代码看起来挺乱的.
    你说说这段代码运行起来有什么问题人家才好回答。你在这里还犯了一个wait和notify使用的错误:
    永远不要的while语句之外调用wait和notify方法
      

  3.   

    意思就是wait和nofity方法要在while语句里调用,而不是if语句
      

  4.   


    说的有点错了:
    一定要从while循环内部调用wait(notify方法一般紧跟在wait的循环之后调用),优先使用notifyAll而不是notify