Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception in thread "main" java.lang.IllegalMonitorStateException

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;
    }
}
like image 431
croutreb Avatar asked May 15 '15 14:05

croutreb


People also ask

How do I resolve Java Lang IllegalMonitorStateException?

The IllegalMonitorStateException can be resolved by calling the wait() , notify() and notifyAll() methods after acquiring an object lock, i.e. within a synchronized block or method.

Which exception is thrown by Wait method?

The IllegalMonitorStateException is related to multithreading programming in Java. If we have a monitor we want to synchronize on, this exception is thrown to indicate that a thread tried to wait or to notify other threads waiting on that monitor, without owning it.

What is Java Lang IllegalStateException?

An IllegalStateException is a runtime exception in Java that is thrown to indicate that a method has been invoked at the wrong time. This exception is used to signal that a method is called at an illegal or inappropriate time.

What is a monitor in Java thread?

Monitor in Java Concurrency is a synchronization mechanism that provides the fundamental requirements of multithreading namely mutual exclusion between various threads and cooperation among threads working at common tasks. Monitors basically 'monitor' the access control of shared resources and objects among threads.


1 Answers

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.

like image 184
MChaker Avatar answered Sep 25 '22 02:09

MChaker