While running this I'm getting IllegalMonitorStateException
because Even thread is trying to notify when it does not have lock on the object isEven
. Why is this happening? A thread should only be able to go inside the synchronized block if it has lock on the object.
public class NumPrinter implements Runnable{
public static Boolean isEven = true;
private boolean isEvenThread;
private int i;
public void run() {
while(i < 100){
synchronized(isEven){
boolean notPrinting = (isEven ^ isEvenThread);
System.out.println(notPrinting);
if(notPrinting) {
try {
isEven.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(i + ",");
i = i+2;
isEven = !isEven;
isEven.notifyAll();
}
}
}
public NumPrinter(boolean isEvenThread) {
this.isEvenThread = isEvenThread;
if(isEvenThread)
i = 0;
else
i = 1;
}
}
public class MultiThreading {
public static void main(String[] args) {
Thread oddt = new Thread(new NumPrinter(false), "Odd");
Thread event = new Thread(new NumPrinter(true), "Even");
event.start();
oddt.start();
}
}