I made this piece of code to try and understand the synchronization between threads in Java, but when I run it I get a java.lang.IllegalMonitorStateException exception. The condition of my code are: 1) A producer cannot produce an item if the cubbyHole contains an item produced by the other producer. 2) The consumer cannot consume an item if the cubby hole is empty. This is the code:
import java.util.*;
public class Esercizio1 {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Consumer c1 = new Consumer(c, 1);
Consumer c2 = new Consumer(c, 2);
Producer p1 = new Producer(c, 10);
Producer p2 = new Producer(c, 20);
p1.start(); p2.start();
c1.start(); c2.start();
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
while (cubbyhole.getAvailable()) {
try {
wait();
} catch (InterruptedException ex) {}
}
for (int i = 1; i < 5; i++) {
int num = number*i;
cubbyhole.put(num);
System.out.println("Producer #" + number + " put: " + num);
}
notifyAll();
cubbyhole.setAvailable(true);
System.out.println("Producer #" + number + " ha finito"); }
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
while (!cubbyhole.getAvailable()) {
try {
wait();
} catch (InterruptedException ex) {}
}
for (int i = 1; i < 5; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + number + " got: " + value);
}
notifyAll();
cubbyhole.setAvailable(false);
System.out.println("Consumer #" + number + " ha finito");
}
}
class CubbyHole {
private int content = -1;
private boolean available = false;
public int get() { return content; }
public void put(int value) { content = value; }
public boolean getAvailable () { return available; }
public void setAvailable (boolean condition) { available = condition; }
}