I was trying to implement the printing of even and odd numbers using two threads problem, not sure if we can put intrinsic locks over a static field of another class, please let me know if this is wrong. But I am getting IllegalMonitorStateException at the notify() method call. The solution to the question asked in the following link - Java Wait and Notify: IllegalMonitorStateException , says to use an synchronized block to own the object's monitor, which I have already done. Still it's not working. As for using the Integer variale, since I am using the Integer wrapper here, it should have worked fine since I am actually instantiating the object for the Integer class : reference. for this : Are Wrapper Classes considered Objects? Or are they just Class? (JAVA). From this I suppose I should be able to acquire and release lock on the Integer variable. Please help me understand what's going wring in my code.
Here's is the code that I tried :
public class PrintOddAndEvenNumbers {
public static volatile Integer count = 0;
public static void main(String[] args) {
Thread t1 = new Thread(new PrintOddNumbers());
Thread t2 = new Thread(new PrintEvenNumbers());
t2.start();
t1.start();
}
}
public class PrintEvenNumbers implements Runnable {
@Override
public void run() {
synchronized (PrintOddAndEvenNumbers.count) {
while (PrintOddAndEvenNumbers.count < 10) {
try {
while (PrintOddAndEvenNumbers.count % 2 == 1) {
wait();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("printing even number : " + PrintOddAndEvenNumbers.count);
PrintOddAndEvenNumbers.count++;
notify();
}
}
}
}
public class PrintOddNumbers implements Runnable {
@Override
public void run() {
synchronized (PrintOddAndEvenNumbers.count) {
while (PrintOddAndEvenNumbers.count < 10) {
try {
while (PrintOddAndEvenNumbers.count % 2 == 0) {
wait();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("printing odd number : " + PrintOddAndEvenNumbers.count);
PrintOddAndEvenNumbers.count++;
notify();
}
}
}
}
Appreciate the help.