Synchronized is the modifier applicable for methods and blocks not for class,constructors,instance blocks,static blocks,classes,variables.
If multiple thread is trying to operate simultaneously on same java object, then there may be arise data inconsistency problem and to overcome with this problem ,we use synchronized keyword. If method is declared as synchronized then at a time only one thread is allowed to execute that method or block on given object so that data inconsistent problem will be resolved. But it increases waiting time of threads and creates performance problems.
Note: If there is no specific requirement then it is not recommended use this keyword
In the above program according to program output should be 2000 because for loop is running for 2000 time but you can see the output here is 1495.
Why? Because suppose when first t1 thread run and update the value of counter so at that time t1 gets counter then value of counter is 0 and update it to +1 and then t2 gets counter value as 1 and update it to 2 then at some time both the t1 and t2 are got same value at a time and so they updated simultaneously value of Counter and it happens many time in the program that’s why its not printing 2000.
So how to solve this by using synchronize keyword. We have to change in method definition of increaseCounter() like this.
public synchronized void increaseCounter()
So that 1 thread complete the task then another get chance to use this method. Then you will get output 2000.