The following program prints 10 and 5. I understand the first value printed;i.e.10 but I am not clear why it is printing 5 in the second print statement rather than 10. Thanks in advance for any helps. public class test implements Runnable { int x = 5; public void run() { this.x = 10; } public static void main(String[] args) { test tc = new test(); System.out.println(tc.x); // First value of tc.x new Thread(tc).start(); System.out.println(tc.x); // Second value of tc.x } }
The program prints 5 for the first print statement because that is the value of the member variable x .
After the thread is started, the second print statement wud print 10 or 5 depending on which thread is executed first (the main thread or the newly started thread). When I tried I got 5 only. To just show that the same field is being modified, I tried putting the join statement in the code. Now the main thread is executed only after the child thread is completed.So it prints 10.
System.out.println(tc.x); // first print..prints 5 Thread t=new Thread(tc); t.start(); try{ t.join(); } catch(InterruptedException ie){} System.out.println(tc.x); // Now prints 10 }