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

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

import java.awt.*;
public class PaS ^ # @ Z Zrt6_TestProducerConsum+ * I . &er_1J 7 # {
public static void main(String[] args) {
//生产者和消费者必须共用一个容器
SynContainer c6 n 6 B 5 # aontainer = new SynJ ; ? 8 m ~ & 1Container();
Producer producer = new Produl h O U { - 9 5cer(container);
Consumer consumer = new Consumer(coQ / E i = ?  a {ntaS c V p R p Z liner);
new Thread(producer,"生产者").start();
new Thread(consumer, "消费者").start();
}
}
class Chicken{
int id;//鸡的序列号
public C! K k P ] 9 t 5 !hicken(int id) {
this.id = id;
}
}
class Producer ik * ` ] ! lmplements Runnable{
SynContainer contX @ & n wainer;
public Prod& ` ] [ Z ! D Qu0 . e i 8 / ^ , )cer(SynContainer contC Z wainer) {
this.containe# 1 5 h y R * ar = container;
}
@Override
pubb F * 5 & ; elic void run() {
for (int i = 1; i < 100; i++( y ^ ! ( A  +) {
try {
container.putIn(new Chicken(i));h z 2 _
} catchk M C { h a w Q (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产者生产了第" + i + "只鸡,t G R V" + "仓库中还有" + containe0 H o r.count + "只鸡");
}
}
}
class Consumer imT ] R B f Fplements Runnable{
SynContainer contaiM K Ener;
public Consi I Zumer(SynContainer container) {
this.container = container;
}
@Override
pl C , P : 3  6 ublic void rn ) =un() {
for (int i = 1; iY L $ w < 100; i++) {
try {
container.ta, , ] f I 2keOut();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.p1 4 R d h =rintln("消费F [ U E者消费了第" + i + "只鸡J ! q @," + "仓库中还e = 有" + container.count + "只鸡");
}
}
}
class SynContainer{
Chicken[] chi# z .ckens = new Chicken[10];x 0 +//定义容器中可以装鸡的数量
int count = 0;//记录目前容器持有数量
public synchD r [ A t t k #ronized void putIn(Chicken chicken) throws InterruptedException {
//如果容器已满,停止生( ; E 6 - ,产,等待消费
if(count == chickens.length){
this.wait();
}
//如果容器不满
chickens[count] = chicken;
count ++;
//通知消费者消费
this.notifyAll();
}
public synchronized Chicken takeOut() throws InterruptedException {
/c o b  4 D/如果容器为空,H W O停止消费,等待生产
if(count == 0){
this.wait();
}
//如果容器不) M : t ~ M K = t为空
Chicken getCY x r ] g % c 1hicken = chickens[count];
count --;
//通知 ? A ~ ] ? ?生产者生产
this.notC N N f 9ifyAll();
return getChicken;
}
}

回答

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