I have the following code:-
package com.amazon.payrollcalculationengineservice.accessor; class ThreadB extends Thread { int total; @Override public void run() { synchronized (this){ for(int i=0; i<5; i++){ total+=i; } } } } public class Solution { public static void main(String[] args) throws InterruptedException { ThreadB b = new ThreadB(); b.start(); synchronized (b){ b.wait(); } System.out.println(b.total); } } Whenever I run this I get my output as 10. If I comment the wait line I get the output as 0 always.
I am confused as to why do I get my answer as 10 always. There are 2 threads , ThreadB and main thread so when I execute the wait method then ThreadB should be waiting as per definition and values should not get added and hence 0 should be printed by main thread then?