买卖商品来介绍:卖家首先要进货上架商品;等待客人来买;客人把商品买完了,需要等待卖家进货上架商品;如此循环
首先建一个代表商品的对象
public class CommondityEntity {
private int num = 0;
private String name = "杯子";
public int getNum() {
return num;
}
public synchronized void add(){
++num;
}
public synchronized void reduce(){
--num;
}
}
代表商人的线程类
public class Merch extends Thread {
private CommondityEntity ce;
public Merch(CommondityEntity ce) {
this.ce = ce;
}
@Override
public void run() {
synchronized (ce) {
try {
super.run();
while (true) {
if (ce.getNum() == 1) {
//进货了,库存已满,等待卖出
ce.wait();
}
if (ce.getNum() == 0) {
ce.add();
//通知买家进货了
ce.notify();
System.out.println("商家进货了!现产品库存为" + ce.getNum() + " 等待卖出!!!");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
代表买家的类
public class Client extends Thread {
private CommondityEntity ce;
public Client(CommondityEntity ce) {
this.ce = ce;
}
@Override
public void run() {
synchronized (ce) {
try {
super.run();
while (true) {
if (ce.getNum() == 0) {
//卖家的货物已经卖光,等待商家进货才能继续购买
ce.wait();
}
if (ce.getNum() == 1) {
ce.reduce();
//通知卖家没货了,需要进货 -- 唤醒线程
ce.notifyAll();
System.out.println(this.getName()+" 购买了一件商品!现产品库存为" + ce.getNum() + " 等待商家进货");
Thread.sleep(1000);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
测试:
public static void main(String[] args) {
CommondityEntity ce = new CommondityEntity();
Thread t = new Client(ce);
t.setName("买家1");
Thread t3 = new Client(ce);
t3.setName("买家2");
Thread t2 = new Merch(ce);
t.start();
t2.start();
t3.start();
}