買賣商品來介紹:賣家首先要進貨上架商品;等待客人來買;客人把商品買完了,需要等待賣家進貨上架商品;如此循環
首先建一個代表商品的對象
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();
}