【发布时间】:2013-01-01 23:48:03
【问题描述】:
我有这样的代码:
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,而是与此有关。 为什么会发生这样的事情?
【问题讨论】:
-
此代码看起来像是您故意造成了竞争条件。这是一个教科书的例子。你为什么要写这个然后问为什么会这样?
-
因为您没有互斥锁(或等效机制)来防止竞争条件。
-
@Matti Virkkunen 我闻到了作业的味道 :-)
-
@sarcan 是的,这是家庭作业;)。我花了很多时间,我仍然不明白,但现在一切都清楚了:)。
标签: java multithreading class static