Exception in thread "main" java.lang.IllegalMonitorStateException

java, multithreading

Solution

In order to deal with the `IllegalMonitorStateException`, you must verify that all invocations of the wait method are taking place only when the calling thread owns the appropriate monitor. The most simple solution is to enclose these calls inside `synchronized` blocks. The synchronization object that shall be invoked in the `synchronized` statement is the one whose monitor must be acquired.

synchronize (sude) {
  sude.wait();
}

For more information and examples, take a look here.

Problem

I am working with `Thread` in `Java` and i get following error - I don't understand why?! Code: ``` import java.util.Random; public class Test { public static void main(String[] args) throws InterruptedException { Vlakno sude = new Vlakno("myName"); // Vlakno = thread class sude.start(); sude.wait(); // ERROR IS ON THIS LINE } } class Vlakno extends Thread { private boolean canIRun = true; private final String name; Vlakno(String name) { this.name = name; } @Override public void run() { while (canIRun) { // System.out.println("Name: " + name); } } public void mojeStop() { System.out.println("Thread "+name +" end..."); this.canIRun = false; } } ```

Original source