Reputation: 1393
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 ");
}
}
Output of this Program is :
1 thrown to main
I am not getting why this thrown to main
came over here.
Upvotes: 5
Views: 4774
Reputation: 10632
You need to call wait
from inside synchronized
block. The current thread should obtain the object's monitor before it waits.
Copied from JavaDoc:
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}
Upvotes: 2
Reputation: 36649
You are getting a java.lang.IllegalMonitorStateException
because the object you are calling wait()
on (t1
) does not own the synchronization lock.
Note that, when you declare a method as synchronized
, the lock owner for that method is the current object (your instance of Bees
in that case). If you want to call wait()
on t1
, you need to synchronize on t1
:
...
Thread t1 = new Thread();
synchronized(t1) {
t1.start();
System.out.print("1 ");
t1.wait(5000);
}
...
On a side note, when catching an exception, you should always include the exception itself to the log output, at least like
...
} catch (Exception e) {
System.out.println("thrown to main" + e);
}
...
Otherwise you might miss important information (such as which exception was actually thrown).
See also The Java™ Tutorials: Synchronization.
Upvotes: 6