В следующем коде потребителя производителя отображается неправильный порядок (до того, как производитель произведет потребительское потребление. Иногда производитель производит много товаров (яма допускает только один товар)).почему это так?
public class CubbyHole {
private int content;
private boolean available=false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {}
}
available = false;
notify();
return content;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
content = value;
available = true;
notifyAll();
}
}
public class Consumer extends Thread {
CubbyHole c;
public Consumer(CubbyHole c){
this.c=c;
}
public void run(){
int val=0;
for(int i =0;i<10;i++){
val=c.get();
System.out.println("consumer gets "+val);
}
}
}
public class Producer extends Thread {
CubbyHole c;
public Producer(CubbyHole c){
this.c=c;
}
public void run(){
for(int i=0;i<10;i++){
c.put(i);
System.out.println("Producer puts "+i);
}
}
}
public class Dimo {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p = new Producer(c);
Consumer con = new Consumer(c);
p.start();
con.start();
}
}
этот код получает следующий вывод
Producer puts 0
Producer puts 1
consumer gets 0
consumer gets 1
Producer puts 2
Producer puts 3
consumer gets 2
consumer gets 3
Producer puts 4
consumer gets 4
consumer gets 5
Producer puts 5
Producer puts 6
consumer gets 6
Producer puts 7
Producer puts 8
consumer gets 7
consumer gets 8
Producer puts 9
consumer gets 9
Может кто-нибудь объяснить, что не так с этим кодом?как получить правильный заказ в этом коде?