日期:2014-05-20 浏览次数:20671 次
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) {