I have code like this:
public class Count extends Thread {
static IntCell n = new IntCell();
public void run() {
int temp;
for (int i = 0; i < 200000; i++) {
temp = n.getN();
n.setN(temp + 1);
}
}
public static void main(String[] args) {
Count p = new Count();
p.setName("Watek1");
Count q = new Count();
p.start();
q.start();
try {
p.join();
q.join();
}
catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("The value of n is " + n.getN());
}
}
class IntCell {
private int n = 0;
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
}
There are two threads and they add 1 to value of n (in static class). When I run this code, the value of n value is never equal to 400000 but something about that.
Why something like this is happening?
This is one of the basic problems of multithreading. Getting a value, incremening it and storing it back is not what is called ‘atomic’ – that is, multiple operations are required to do this. What happens here is: One thread obtains N at value X, the other thread does so as well. Both threads increment, and store X+1 as new N – although both incremented their local count by one, N was also just incremented by one.
Whether or not this happens and how much N will deviate from the expected value is, for arguments sake, random.
Check out classes like AtomicInteger and read up on things called mutexes.