Following producer consumer code displays a wrong order(before producer produce consumer consumes. sometimes producer produce many items(cubbyhole allows one item only)). why is that?
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();
}
}
this code gets the following output
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
can anyone explain what is wrong with this code? how to get the correct order in this code?
Check these two lines:
val=c.get();
System.out.println("consumer gets "+val);
What can happen is the consumer calls the cubby hole and waits there while it is free. It then gets the value and releases it. Now between these two lines - after c.get() and before the printlin the other thread can finish its whole process - call put(i) and print. That's when you will get two producer.put() values.
You should move the printing part inside the cubby hole code to make sure it prints what you want.