I'm doing a simple exercise to understand the concept of threads and synchronization. But I don't know whether the code is correct or not.
public class PopcornMachine {
// shared resource
private boolean isBinFull = false;
// producer method
public synchronized void placePopcorn () throws InterruptedException {
while (true) {
while (!isBinFull) wait ();
isBinFull = true;
System.out.println(isBinFull);
notify ();
Thread.sleep(1000);
}
}
// consumer code
public synchronized void takePopcorn () throws InterruptedException {
while (true) {
while (isBinFull) wait ();
isBinFull = false;
System.out.println(isBinFull);
notify ();
Thread.sleep(1000);
}
}
}
public class PopcornDemo {
public static void main (String[] args) throws InterruptedException{
final PopcornMachine machine = new PopcornMachine();
Thread produce = new Thread (new Runnable() {
public void run() {
try {
machine.placePopcorn ();
} catch(InterruptedException e) {}
}
});
Thread consume = new Thread (new Runnable() {
public void run() {
try {
machine.takePopcorn ();
} catch(InterruptedException e) {}
}
});
produce.start();
consume.start();
produce.join();
consume.join();
}
}
The answer I have is: false false false false false false
But it feels wrong. Isn't there a true value should come in the middle of the code?