1

Question: I have two thread classes as below. I was expecting my program to never terminate since I have not used wait(long ms) method. As I am not calling notify the object which has acquired the lock and is in wait state should have never been notified.

But the output is not as per my expectation.

Please help me in understanding this concept.

My code:

    ThreadA{
    main(String args[]){
    ThreadB b = new ThreadB();
    b.start();
    }
    synchronized(b) {
                try {
                    System.out.println("Main thread will start waiting");
                    b.wait();
                    System.out.println("Main thread waiting for notification");
                    System.out.println("wait over!!");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                System.out.println(b.total);
                System.out.println("Main thread execution finished!!");
            }
    }

    ThreadB{
    int total =0;
        public void run() {
            synchronized(this) {
                for(int i=0;i<=100;i++) {
                    total=total+i;
                }
                System.out.println("Child thread should give notification");
                //this.notify();
            }
            System.out.println("Child thread execution finished!!");
        }
    }
 <!--code-->   

Result:

    Main thread will start waiting
    Child thread should give notification
    Child thread execution finished!!
    Main thread waiting for notification
    wait over!!
    5050
    Main thread execution finished!!
Annie
  • 9
  • 3
  • 1
    "But the output is not as per my expectation" - This is something that you might want to include! – Jacob G. Apr 08 '18 at 19:20

0 Answers0