Exception in thread "main" java.lang.IllegalMonitorStateException

I work with Threadin Javaand I get the following error: I don’t understand why ?!

the 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;
    }
}
+4
source share
2 answers

To deal with IllegalMonitorStateException, you must make sure that all calls to the wait method are made only when the calling thread owns the appropriate monitor. The simplest solution is to enclose these calls inside blocks synchronized. The synchronization object that should be called into the synchronizedoperator is the one whose monitor should be acquired.

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

For more information and examples, see here .

+4
source

From Java docs Object.wait

IllegalMonitorStateException - .

sude.start(); : sude. .

, , :

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

All Articles