java 生产者消费者问题

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

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

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

        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值