我正在尝试理解并发编程,但我不确定一件事。我有一个有两个线程的程序,它们递增相同的 int (IntCell n)。在 200 000 次循环之后 int 应该是 400 000,但它有点超过 200 000 ,然后将其递增并将其设置为 int 两次(设置相同 int 的两次操作)。这是代码:
class IntCell {
private int n = 0;
public int getN() {return n;}
public void setN(int n) {this.n = n;}
}
class Count extends Thread {
private static IntCell n = new IntCell();
@Override
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();
Count q = new Count();
p.start();
q.start();
try { p.join(); q.join(); }
catch (InterruptedException e) { }
System.out.println("The value of n is " + n.getN());
}
}
守候你守候我
缥缈止盈
相关分类