Swati,
It is possible for the output to be 10 without calling sleep. the concept is if you run some code between new Thread(tc).start(); // 1
and System.out.println(tc.x)
which cause a big enough delay so the run() get excuted before you print tc.x.
I add one for loop to simulate the delay, then run it 10 times.
possible Result :
10,5,5,5,10,5,5,10,5,5
public class TestClass implements Runnable
{
int x = 5;
public void run()
{
this.x = 10;
}
public static void main(String[] args)
{
for (int j=0; j<10;j++) {
TestClass tc = new TestClass();
new Thread(tc).start(); // 1
for (int i=0; i<500000;i++){ }
System.out.println(tc.x);}
}
}
Originally posted by swati gupta:
will it always print 5 or there is possibility that the thread may get chance to run (without calling sleep on main) and it might print 10