音乐电台 2020-09-11 16:37 采纳率: 100%
浏览 98
已采纳

萌新求问,大佬们看下这个为什么会偶尔出现数组越界的情况?

#生产者和消费者应当共用container的count,但是会偶尔出现数组下标越界和count不匹配

import java.awt.*;

public class Part6_TestProducerConsumer_1 {
    public static void main(String[] args) {
        //生产者和消费者必须共用一个容器
        SynContainer container = new SynContainer();
        Producer producer = new Producer(container);
        Consumer consumer = new Consumer(container);
        new Thread(producer,"生产者").start();
        new Thread(consumer, "消费者").start();
    }
}

class Chicken{
    int id;//鸡的序列号
    public Chicken(int id) {
        this.id = id;
    }
}

class Producer implements Runnable{
    SynContainer container;

    public Producer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            try {
                container.putIn(new Chicken(i));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("生产者生产了第" + i + "只鸡," + "仓库中还有" + container.count + "只鸡");
        }
    }
}

class Consumer implements Runnable{
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            try {
                container.takeOut();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("消费者消费了第" + i + "只鸡," + "仓库中还有" + container.count + "只鸡");
        }
    }
}

class SynContainer{
    Chicken[] chickens = new Chicken[10];//定义容器中可以装鸡的数量
    int count = 0;//记录目前容器持有数量

    public synchronized void putIn(Chicken chicken) throws InterruptedException {
        //如果容器已满,停止生产,等待消费
        if(count == chickens.length){
            this.wait();
        }
        //如果容器不满
        chickens[count] = chicken;
        count ++;
        //通知消费者消费
        this.notifyAll();
    }

    public synchronized Chicken takeOut() throws InterruptedException {
        //如果容器为空,停止消费,等待生产
        if(count == 0){
            this.wait();
        }
        //如果容器不为空
        Chicken getChicken = chickens[count];
        count --;
        //通知生产者生产
        this.notifyAll();
        return getChicken;
    }
}
  • 写回答

2条回答 默认 最新

  • 半路出码 2020-09-11 17:28
    关注

    count ++;count --; 都不是原子操作的。换成AtomicInteger

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器