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;
}
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With