首先定義一個商品類:
public class Product {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString(){\\重寫tostring方法
return "ID是"+id+"的產品。";
}
}
設置一個倉庫,用來放置生產的商品
public class storage {
Product [] ps=new Product[10];//此處設置了倉庫的容量,只能放置10個商品
int index=0;
public synchronized void push(Product p) {
while(index==ps.length){
try {
this.wait();//當倉庫已滿時,暫停商品的生產,等待消費者購買
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ps[index]=p;
index++;
this.notifyAll();//通知消費者倉庫中已有商品,可以購買了
}
public synchronized Product pop() {
while(index==0){
try {
this.wait();//當倉庫沒有商品時,消費者暫停購買,等待生產者生產
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
Product p=ps[index];
this.notifyAll();//通知生產者倉庫未滿,可以繼續生產了
return p;
}
}
定義一個生產者類
public class Producer implements Runnable{//實現runnable接口
private storage store=null;
public Producer(storage store){//定義含參的構造方法
this.store=store;
}
public void run() {重寫run方法
int i=0;
while(true){
Product p=new Product();
i++;
p.setId(i);
store.push(p);//調用倉庫類的方法實現生產
}
}
}
定義一個消費者類:
public class Customer implements Runnable{
private storage store=null;
public Customer(storage store){
this.store=store;
}
public void run() {
for(int i=0;i<1000;i++){
Product p=store.pop();//調用倉庫類的方法實現購買
System.out.println("消費者購買了"+p);
}
}
}
最後寫一個測試類進行測試
public class test {
public static void main(String[] args) {
storage store=new storage();
Producer p=new Producer(store);
Customer c=new Customer(store);
Thread t1=new Thread(p);//創建線程對象
Thread t2=new Thread(c);
t1.start();//線程啓動
t2.start();
}
}