多线程生产者与消费者问题

/*多线程经典问题
* 生产者和消费者:
*   1.生产者边生产,消费者边消费
*   2.仓库满了则暂停生产,仓库空了就暂停消费。
*       【使用wait()方法:使得当前线程立刻停止运行,处于等待状态(WAIT),并将当前线程置入锁对象的等待队列中,直到被通知(notify)或被中断为止。】
*   3.发生生产后,通知对方消费。发生消费后,通知对方生产。
*       【使用:notifyAll()方法;唤醒所有处于等待状态的线程---或者:notify()方法:唤醒处于等待状态的线程】
* */
public class ProducerAndConsumer{
    public static void main(String[] args) {
        BufferZone bufferZone = new BufferZone();
        new Producer(bufferZone).start();
        new Consumer(bufferZone).start();
    }


}
//生产者
    class Producer extends Thread{
        BufferZone bufferZone;
        public Producer(BufferZone bufferZone){
            this.bufferZone = bufferZone;
        }
        //生产
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {

                bufferZone.push(new Product(i));
                System.out.println("生产了第"+(i+1)+"个产品");
            }
        }
    }
    //消费者
    class Consumer extends Thread{
        BufferZone bufferZone;
        public Consumer(BufferZone bufferZone){
            this.bufferZone = bufferZone;
        }
        //消费
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
//                try {
//                    sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                bufferZone.pop();
                System.out.println("消费了第"+(i+1)+"个产品");
            }
        }
    }
    //产品
    class Product{
        //产品编号
        int id;
        public Product(int id) {
            this.id = id;
        }
    }
    //缓冲区
    class BufferZone{
        //可以理解为仓库,设置一个为大小为10的仓库
        Product[] storehouse = new Product[10];
        int num = 0;
        //生产者生产产品
        public synchronized void push(Product product){
            if (num==storehouse.length){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            storehouse[num] = product;
            num++;
            //生产了产品,通知消费者消费(相当于将处于wait()状态的消费者线程唤醒)
            this.notifyAll();
        }
        //消费者消费产品
        public synchronized Product pop(){
            //判断有没有产品
            if (num==0){
                //没有的话,等待生产者生产产品
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //消费产品
            num--;
            Product product = storehouse[num];
            //消费了产品,通知生产者生产
            this.notifyAll();
            return product;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值