Following code gives a fixed output as 400000000 whereas when I am removing static keyword from synchronized addOne method I am getting random output any integer less that 400000000.
Can anyone please explain that ?
public class ThreadTest extends Thread{
public static int sharedVar = 0;
private static synchronized void addOne()
{
for (int i = 0; i < 200000000; i++)
{
sharedVar++;
}
}
@Override
public void run()
{
addOne();
}
public static void main(String[] args)
{
ThreadTest mt1 = new ThreadTest();
ThreadTest mt2 = new ThreadTest();
try
{
// wait for the threads
mt1.start();
mt2.start();
mt1.join();
mt2.join();
System.out.println(sharedVar);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
}
}