废话不多说,案例如下

 package com.xujingyang.Exok;

 /**
* 商品类
* @author 徐景洋
*/
public class Goods {
private String pinpai;
private String name; private int num; public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getPinpai() {
return pinpai;
}
public void setPinpai(String pinpai) {
this.pinpai = pinpai;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} }
 package com.xujingyang.Exok;

 /**
* 生产商类
* @author 徐景洋
*/
public class Producer implements Runnable {
private Goods goods; public Goods getGoods() {
return goods;
} public void setGoods(Goods goods) {
this.goods = goods;
} @Override
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (goods) {
if(goods.getNum()>0){
try {
goods.wait();//商品数量已经大于0啦,消费者要取货咯,自己就开始等待咯
} catch (InterruptedException e) {
e.printStackTrace();
}
} if (i % 2 == 0) {
goods.setPinpai("哇哈哈");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
goods.setName("矿泉水"); } else {
goods.setPinpai("旺仔");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
goods.setName("小馒头");
}
goods.setNum((goods.getNum()+1));
System.out.println("生产了" + goods.getPinpai() + goods.getName());
goods.notify();//商品不够啦,自己生产完,然后通知消费者取货咯
}
}
} }
 package com.xujingyang.Exok;

 /**
* 消费者类
* @author 徐景洋
*/
public class Customer implements Runnable { private Goods goods; public Goods getGoods() {
return goods;
} public void setGoods(Goods goods) {
this.goods = goods;
} @Override
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (goods) {
if(goods.getNum()<=0){
try {//如果商品生产的数量小于0,则开始等待.只有有货才能购物嘛
goods.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
goods.setNum((goods.getNum()-1));
System.out.println("取走了" + goods.getPinpai() + goods.getName());
goods.notify();//取走之后通知生产商继续生产商品(唤醒在对象锁等待池中的线程继续执行)
}
}
} }
 package com.xujingyang.Exok;

 /**
* 测试类
* @author 徐景洋
*/
public class Test {
public static void main(String[] args) {
Goods goods=new Goods(); //生产者生产商品
Producer p=new Producer();
p.setGoods(goods); //消费者取走商品
Customer c=new Customer();
c.setGoods(goods); new Thread(p).start();
new Thread(c).start();
}
}

清晰明了不,嘿嘿

05-21 07:27