I have doubt in the following piece of code. In this i expect race condition to occur for both the static variables 'a' and 'b' and the expect the output for both the variables to be less than 1000. However, the expected behaviour is not observed when i execute the below code as shown i.e. the output for b is always 1000. But, when i uncomment the lines marked with arrows and execute the below code, the race condition is observed for both the variables i.e the output for both the variables 'a' and 'b' is less than 1000. Need help with the same. Pardon me if i have missed out or ignored any of the basic or elementary concepts of threading considering the fact that i am still a newbie to java threads !!!
public class SampleRace {
public static void main(String[] args) {
// TODO Auto-generated method stub
SampleRace1 a = new SampleRace1();
SampleRace1 b = new SampleRace1();
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(SamapleLoop.a); // <---------------------
System.out.println(SampleRace1.b);
}
}
class SamapleLoop {
public static int a = 0;
public static void loop() {
a++;
}
}
class SampleRace1 implements Runnable {
public static int b = 0;
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i <= 500; i++) {
//SamapleLoop.loop(); // <------------------------
b++;
}
}
}