I'm working on a small game to be played through discord by me and some friends.
My code should theoretically work, but for some reason I can't escape the IllegalMonitorStateException "current Thread is not owner" caused by the wait() method below.
public void waitForMethod () { Thread thread = new Thread() { @Override public void run () { synchronized(lock) { while (true) { if (methodDone) { methodDone = false; channel.sendMessage("methodDone = true").queue(); break; } else { channel.sendMessage("methodDone = false").queue(); try { wait(); channel.sendMessage("successfully notified.").queue(); } catch (InterruptedException e) {} } } } } }; thread.run(); channel.sendMessage("exited Thread.").queue(); } So far, I've been able to get all but the "successfully notified" message and "methodDone = true" to send, obviously because as soon as it calls "wait();" it raises the IllegelMonitorStateException "current Thread is not owner."
Below is the code that relies on the "waitForMethod()" method.
@Override public void onMessageReceived (MessageReceivedEvent event) { synchronized(lock) { handleEvent(event); lock.notify(); } } To be clear, waitForMethod is called by a class that represents the game's loop, and is simply meant to make the game loop pause until a variable has been changed by the "handleEvent()" method to true, in which case it should continue the game's loop.
I'm basically just looking for a way to pause a section of code until another section of code tells it to unpause.
I tried using the EventWaiter, but I couldn't find a way to properly set up the dependencies or import it, so I kind of gave up and went with something I'm at least somewhat familiar with.
lock.wait()instead ofwait()wait()is shorthand for writingthis.wait()Ifthiswas the object that the other thread was going to notify (which, in your case, it isn't) then the unadornedwait()call would work inside of asynchronized(this)block.ifthe condition has not been met. As a matter of good hygiene, you should always call itwhilethe condition is not met. This comment box is too small for me to explain why, but you should never rely on the condition being satisfied whenwait()returns. You should always re-check it, andwait()again if necessary.