参考代码:
package aaa;
public class Goods {
private String name;
private String brand;
boolean isFlag;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Goods(String name, String brand) {
super();
this.name = name;
this.brand = brand;
}
public Goods() {
super();
}
public synchronized void set(String name,String brand) {
if (isFlag) {
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.setName(name);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.setBrand(brand);
System.out.println("生产者线程生产了"+this.getBrand()+"-----"+this.getName());
super.notify();
isFlag=true;
}
public synchronized void get() {
if (!isFlag) {
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消费者线程取走了---"+getBrand()+"---"+getName());
super.notify();
isFlag=false;
}
}
package aaa;
public class Product implements Runnable{
public Product(Goods goods) {
super();
this.goods = goods;
}
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
private Goods goods;
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2!=0) {
goods.set("旺仔", "小馒头");
}else {
goods.set("哇哈哈", "矿泉水");
}
}
}
}
package aaa;
public class Custmer implements Runnable{
private Goods goods;
public Custmer() {
super();
}
public Custmer(Goods goods) {
super();
this.goods = goods;
}
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
public void run() {
for (int i = 0; i < 20; i++) {
goods.get();
}
}
}
package aaa;
public class Test {
public static void main(String[] args) {
Goods goods = new Goods();
Product product = new Product(goods);
Custmer custmer = new Custmer(goods);
Thread t1 = new Thread(product);
Thread t2 = new Thread(custmer);
t1.start();
t2.start();
}
}