Exception from java method for wait ()

public class Bees { public static void main(String[] args) { try { new Bees().go(); } catch (Exception e) { System.out.println("thrown to main" + e); } } synchronized void go() throws InterruptedException { Thread t1 = new Thread(); t1.start(); System.out.print("1 "); t1.wait(5000); System.out.print("2 "); } } 

The output of this program:

 1 thrown to main 

I do not understand why this thrown to main came here.

+5
source share
2 answers

You get java.lang.IllegalMonitorStateException because the object you call wait() on ( t1 ) does not have a synchronization lock.

Note that when you declare a method as synchronized , the owner of the lock for this method is the current object (your Bees instance in this case). If you want to call wait() on t1 , you need to synchronize with t1 :

 ... Thread t1 = new Thread(); synchronized(t1) { t1.start(); System.out.print("1 "); t1.wait(5000); } ... 

On the side of the note, when you catch an exception, you should always include the exception itself in the output of the log, at least as

 ... } catch (Exception e) { System.out.println("thrown to main" + e); } ... 

Otherwise, you can skip important information (for example , which was excluded).

See also Java ™ Tutorials: Synchronization.

+5
source

You need to call wait from within the synchronized block. The current thread must receive the monitor of the object before waiting.

Copied from JavaDoc :

The current thread must own this object. The thread frees the owner of this monitor and waits until another thread tells the threads waiting on this object monitor to wake up either through a call to the notification method or the notifyAll method. The thread then waits until it can re-acquire ownership of the monitor and resume execution.

 synchronized (obj) { while (<condition does not hold>) obj.wait(); ... // Perform action appropriate to condition } 
+2
source

Source: https://habr.com/ru/post/1238945/


All Articles