I'm trying to understand what thread interference is. This is an explanation about thread interference from Java official site.
Thread A: Retrieve c.
Thread B: Retrieve c.
Thread A: Increment retrieved value; result is 1.
Thread B: Decrement retrieved value; result is -1.
Thread A: Store result in c; c is now 1.
Thread B: Store result in c; c is now -1.
so I added codes to see c's changes.
In the picture(4th line), Shouldn't 1th decrement:(Retrieve C) 0 be -1? why it's 0?
Also, if you see this below result, 2th decrement:(Retrieve C) is -1.
I think 2th decrement(Decreased C) should be -2, but it's still -1.
I don't understand. Can someone explain my reslt?
2th decrement:(Retrieve C) -1
2th decrement(Decreased C) -1
public class Counter {
private int c = 0;
public void increment(){
for(int i=0; i<1000; i++){
System.out.println(i + "th increment:(Retrieve C) " + c);
c++;
System.out.println(i + "th increment:(Increased C) " + c);
}
}
public void decrement(){
for(int i=0; i<1000; i++){
System.out.println(i + "th decrement:(Retrieve C) " + c);
c--;
System.out.println(i + "th decrement(Decreased C) " + c);
}
}
public int getC(){
return c;
}
public static void main(String[] args) throws InterruptedException{
Counter c = new Counter();
Thread t1 = new Thread(() -> {
c.increment();
});
Thread t2 = new Thread(() -> {
c.decrement();
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
