5
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.

akash
  • 22,664
  • 11
  • 59
  • 87
Avinash Jadhav
  • 1,243
  • 2
  • 12
  • 20
  • may be you should have check this:http://stackoverflow.com/questions/1537116/illegalmonitorstateexception-on-wait-call – soorapadman Dec 22 '15 at 11:28
  • Do you understand what the `wait()` method does? – Kayaman Dec 22 '15 at 12:06
  • @Kayaman Its pleasure if you give me some idea about wait() method. – Avinash Jadhav Dec 23 '15 at 04:03
  • It looks like you're trying to use it as some sort of general pause method. If you're not familiar with the `wait()/notify()` mechanism, I recommend doing a search here, there are plenty of great explanations. – Kayaman Dec 23 '15 at 07:01

2 Answers2

6

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.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
2

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
 }
Debojit Saikia
  • 10,532
  • 3
  • 35
  • 46