Search code examples
javamultithreadingwait

Thread come out from waitting state without notify() in multithreading


How can below code get executed as ThreadB not executing notify(),ThreadA should remain in waitting state. Is it possible that a thread can come out from waitting state as the another thread completes its execution.

public class ThreadA extends Thread
{
    public static void main(String[] args)
    {
        ThreadB B = new ThreadB();
        B.start();
        synchronized (B) {
            try {
                /* Go into waiting state */
                B.wait();
            } catch (InterruptedException e) {
            }

            System.out.println(B.result);
        }
    }
}

class ThreadB extends Thread
{
    int result;

    public void run()
    {
        synchronized (this) {
            for (int i = 0; i <= 10; i++) {
                result = result + i;
            }
            // notify();
        }
    }
}

Output:

55

Solution

  • If you go to the JavaDocs (http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()) and read the documentation for Thread you will see that it says never to use wait, notify, or notifyAll on a Thread. Internally, Thread.join() and thread death use wait and notifyAll to accomplish the join functionality