I wonder why the following code throws java.lang.IllegalMonitorStateException
when I lock myInt
.
package Thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadingTest1 {
public Integer myInt = 0;
public Object lock = new Object();
public void alternativePrinting() throws InterruptedException {
Thread thread1 = new Thread(() -> {
while(myInt <= 100)
synchronized (myInt){
if(myInt % 2 == 0) {
System.out.println(Thread.currentThread().getName() + " prints " + myInt);
myInt++;
myInt.notify();
}
else
try {
myInt.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
while(myInt <= 100)
synchronized (myInt){
if(myInt % 2 == 1) {
System.out.println(Thread.currentThread().getName() + " prints " + myInt);
myInt++;
myInt.notify();
}
else
try {
myInt.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// ExecutorService threadPool = Executors.newFixedThreadPool(2);
// threadPool.submit(thread1);
// threadPool.submit(thread2);
// threadPool.shutdown();
thread1.start();;
thread2.start();
}
public static void main(String[] args) throws InterruptedException {
MultiThreadingTest1 multiThreadingTest1 = new MultiThreadingTest1();
multiThreadingTest1.alternativePrinting();
}
}
Execeptions:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.base/java.lang.Object.notify(Native Method)
at Thread.MultiThreadingTest1.lambda$alternativePrinting$0(MultiThreadingTest1.java:18)
at java.base/java.lang.Thread.run(Thread.java:835)
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.base/java.lang.Object.notify(Native Method)
at Thread.MultiThreadingTest1.lambda$alternativePrinting$1(MultiThreadingTest1.java:34)
at java.base/java.lang.Thread.run(Thread.java:835)
I know lock lock
will be OK.
But I wonder why the following code throws java.lang.IllegalMonitorStateException
when I lock myInt