Here I am using synchronized for common counter variable for both threads t1, t2 but even though counter value getting as inconsistency, please can any one explain why it's giving results like this and give a solution.
public class Sync {
public static int counter = 0;
private static synchronized void increment() {
++counter;
}
public static void process() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++)
increment();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++)
increment();
}
});
t1.start();
t2.start();
}
public static void main(String[] args) {
process();
System.out.println("counter is:: " + counter);
}
}
It should give counter value as 2000.