public class TestOne {
public static void main(String[] args) {
Container container=new Container();
new Producier(container).start();
new Customer(container).start();
}
}
//生產者
class Producier extends Thread{
Container container;
public Producier(Container container){
this.container=container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生產了-->"+i+"只雞");
}
}
}
//消費者
class Customer extends Thread{
Container container;
public Customer(Container container){
this.container=container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("取出了"+container.pop().id+"只雞");
}
}
}
//商品id
class Chicken{
//商品id
int id;
public Chicken(int id) {
this.id = id;
}
}
//緩沖區
class Container{
//宣告容器大小
Chicken[] chickens=new Chicken[10];
//容器內的個數
int count=0;
//生產者放東西
public synchronized void push(Chicken chicken) {
if(count==10){
//通知消費者消費
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//往倉庫添加東西
chickens[count]=chicken;
count++;
//通知消費者消費
this.notifyAll();
}
//消費者取東西
public synchronized Chicken pop(){
if(count==0){
//等待生產者生產
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消費
Chicken chicken=chickens[count];
count--;
//通知生產者生產
this.notifyAll();
return chicken;
}
}
Exception in thread "Thread-1" java.lang.ArrayIndexOutOfBoundsException: 10
at Day05.Container.pop(TestOne.java:97)
at Day05.Customer.run(TestOne.java:46)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/276048.html
標籤:Java相關
