今天想寫數據庫的一個應用的,因爲涉及到加鎖解鎖設計,我就查了查生產中消費者問題,自己寫了一下。
首先,有一個倉庫,也就是一個當做緩衝區的東西
public class WareHouse {
private int products[];
private String name;
private int base = 0;
private int top = 0;
private int capacity;
public WareHouse(int capacity, String name) {
products = new int[capacity];
this.name = name;
this.capacity = capacity;
}
public synchronized int pop() {
int product = 0;
if (top == base) {
try {
System.out.println("倉庫空了,快點來生產啊");
wait();
} catch (InterruptedException e) {
System.out.println("stop push");
}
}
if(top!=base){
product = products[top--];
System.out.println("消費了一個產品"+product);
notify();
}
return product;
}
public synchronized void push(int n) {
if (top == capacity - 1) {
try {
System.out.println("倉庫滿了,快點來消費");
wait();
} catch (InterruptedException e) {
System.out.println("stop push");
}
}
products[++top] = n;
System.out.println("生產了一個產品 "+n);
notify();
}
public int[] getProducts() {
return products;
}
public String getName() {
return name;
}
}
然後是生產者和消費者
public class Producer extends Thread {
private int no;
private WareHouse wareHouse;
public Producer(int no, WareHouse house) {
this.no = no;
this.wareHouse = house;
}
@Override
public void run() {
this.excuteProduce();
}
private void excuteProduce() {
int i = 0;
while (true) {
wareHouse.push(i);
// System.out.println(no + "我生產了一個產品" + i);
try {
Thread.sleep(1000);
} catch (Exception e) {
return;
}
++i;
}
}
}
public class Consumer extends Thread {
private int no;
private WareHouse wareHouse;
public Consumer(int no, WareHouse house) {
this.no = no;
wareHouse = house;
}
@Override
public void run() {
excuteConsume();
}
private void excuteConsume() {
while (true) {
int n=this.wareHouse.pop();
// System.out.println("我消費了"+n);
try {
Thread.sleep(1000);
}catch (Exception e){
return;
}
}
}
}