Please refer the below code where 200 threads are trying to increment the counter variable simultaneously.
The program tries to do the same 100 times. It prints the value of variable in case the incremented value doesn't reach to 200 - meaning some threads interfered with each other.
To avoid interference, I used synchronized keyword. It works well if I use synchronized on static lock object (commented line), but if I use synchronized on counter variable, I still see many times the value doesn't get incremented to 200.
import java.util.ArrayList;
import java.util.List;
public class Class {
    public static Integer counter = new Integer(0);
    
    //public static Object lock = new Object();
    static void increment() {
        synchronized (counter) {
            counter++;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        for (int j = 0; j < 100; j++) {
            counter = 0;
            List<Thread> list = new ArrayList<>();
            for (int i = 0; i < 200; i++) {
                Thread t = new Thread(() -> increment());
                list.add(t);
                t.start();
            }
            for (Thread t : list) {
                t.join();
            }
            if (counter < 200){
                System.out.println(counter);
            }
        }
    }
}
What is the reason for such behaviour?
 
     
     
    