Here's my thread:
public class MyRunnable implements Runnable
{
public static int num = 0;
private void add()
{
num = num + 1;
}
@Override
public void run()
{
for (int i=0;i<10000;i++)
{
add();
System.out.println(num);
}
}
}
And here's my main:
public class MultiThread
{
public static void main(String[] argv)
{
Thread mt1 = new Thread(new MyRunnable(), "A");
Thread mt2 = new Thread(new MyRunnable(), "B");
mt1.start();
mt2.start();
}
}
I'm expecting to see race conditions there and therefore the output should be less than 20000. However, the actual output I got was :
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
Process finished with exit code 0
Can anyone explain to me why in this java program the add operation seems to be atomic even when I didn't do any locking or synchronizing?