我有这样的代码:
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;
}
}
有两个线程,它们将 n 的值加 1(在静态类中)。当我运行此代码时,n 值的值永远不会等于 400000,而是与此有关。为什么会发生这样的事情?