java 生产者消费者问题

来源:互联网 发布:淘宝小蜜在哪里 编辑:程序博客网 时间:2024/05/22 03:51

今天想写数据库的一个应用的,因为涉及到加锁解锁设计,我就查了查生产中消费者问题,自己写了一下。

首先,有一个仓库,也就是一个当做缓冲区的东西

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;            }        }    }}


0 0
原创粉丝点击