I'm testing some java multithreading things, and I ran into this problem : I have a Thread that calls a method of Producer class and that method has a synchronized block locked on the object I passed in the constructor. App.class :
public class App {
public static void main(String[] args) {
Object lock = new Object();
Producer producer = new Producer(lock);
Thread producerThread = new Thread(new Runnable() {
@Override
public void run() {
producer.produce();
}
});
producerThread.start();
try {
producerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Producer class :
public class Producer {
private final Object lock;
public Producer(Object lock) {
this.lock = lock;
}
public void produce() {
synchronized (lock) {
System.out.println("Producer started ...");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Producer resumed");
}
}
}
And I get :
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.base/java.lang.Object.wait(Native Method)
at java.base/java.lang.Object.wait(Object.java:328)
at Producer.produce(Producer.java:13)
at App$1.run(App.java:15)
at java.base/java.lang.Thread.run(Thread.java:844)
Process finished with exit code 0
So, what happens when I pass a lock object through the constructor, and why its not working?