So I am looking at an IBM Article and I couldn't get my head around with the below statements.
public class Counter {
private int counter = 0;
public int get() { return counter; }
public void set(int n) { counter = n; }
public void increment() {
set(get() + 1);
}
}
What happens if two threads try to execute increment() at the same time? The counter might be incremented by 1 or by 2.
My doubts is that if a Thread A executes the above statement for the first time, then get() will return 0 and set increment will set it to 1. Only after the thread A finish executing or goes to sleep, Thread B can start executing ? How come both Thread A and Thread B can execute a piece of code at the same time ? How can counter be incremented by 2 ?