0

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();

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.