multithreading - Exception in thread "main" java.lang.IllegalMonitorStateException -
i working thread
in java
, following error - 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 on 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; } }
in order deal
illegalmonitorstateexception
must verify invokations of wait method taking place when calling thread owns appropriate monitor. simple solution enclose these calls insidesynchronized
blocks. synchronization object shall invoked insynchronized
statement 1 monitor must acquired.
synchronize (sude) { sude.wait(); }
for more informations , examples, take here.
Comments
Post a Comment