MD Tate
MD Tate

Reputation: 9

Java IllegalMonitorStateException when using thread.wait();

I'm new to using threads I get an IllegalMonitorStateException as soon as the wait method is called can someone help me out

public class SomeClass{

    private final Thread thread = new Thread(this::someMethod);

    public synchronized void someMethod(){
        try {
            doSomething();
            TimeUnit.SECONDS.sleep(2);
            doSomething();
            thread.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        someMethod();
    }

    public synchronized void restartThread() {
        thread.notify();
    }
        SomeClass test = new SomeClass();
        test.start();

Upvotes: 0

Views: 51

Answers (1)

Mirek Pluta
Mirek Pluta

Reputation: 8003

wait and notify methods can only be called on the monitor object, for which you have acquired a lock. In your case you acquired a lock on the object of type SomeClass, however you try to call those methods on the monitor of the thread object. Instead you should just call wait(); and notify(); in your code, which will call them on this object, which is exactly the same object for which you acquired a lock with synchronized keyword on the methods.

Upvotes: 1

Related Questions