Search code examples
javamultithreadingthreadpoolwait

Why wait method doesn't work on Thread object?


Thread t2 = new Thread();
Thread t3 = new Thread();

t1.start();
t2.start();
synchronized (t2) {
    t2.wait(20000);
}
t3.start();

The above program runs without t2 waiting for 20sec. I observed that when thread object is started then it wont wait. Why is this happening?


Solution

  • Why is this happening?

    First, let's be clear. This function call, t2.wait(20000) does not do anything to the t2 thread. In fact, it doesn't really do anything at all. All it does is not return until either one of two things happens;

    • Some other thread calls t2.notify(), or
    • 20 seconds elapse.

    If the call took less than 20 seconds to return, then that's probably because the t2 thread itself called t2.notify() just before it died. In most implementations of the Java standard library, the join() method is implemented by using wait() and notify() calls on the thread object.

    (Note: most authors will advise you not to ever call wait() or notify() on a Thread instance precisely because of the potential for interference between your code and the library code when both call the same methods on the same instance.)

    The above program runs without t2 waiting for 20sec.

    As somebody else already has pointed out here, You have not provided any run() method for your t2 thread, so it's unclear why you would expect the t2 thread to "wait" or, to do anything else at all. The only thing a thread ever does is execute the code that you provide for it in a run() method.

    The default Thread.run() method would call the run() method of a delegate object that you supply when you construct the threads, but your code supplies no delegate. In that case, the default run() method does nothing at all.