我有一个类,每个在自己的线程上创建许多新对象,我想保持跨线程的运行计数。我想要一个,AtomicInteger
但它没有达到我的预期,而是得到了一个更小的版本。我假设这是一个竞争条件错误 - 但我不完全确定。
A 创建了这个测试示例,它重新创建了我想要做的事情。
public class Test {
public static void main(String args[]) {
AtomicInteger total = new AtomicInteger(0);
for (int i = 0; i < 10; i++) {
DoThing doThing = new DoThing();
Thread thread = new Thread(doThing);
thread.start();
total.addAndGet(doThing.getTally());
}
System.out.println(total.get());
}
}
class DoThing implements Runnable {
int tally = 0;
@Override
public void run() {
for(int i = 0; i< 100; i++) {
tally++;
}
System.out.println("Tally is " + tally);
}
public int getTally() {
return tally;
}
}
但是,这会输出:
Tally is 100
Tally is 100
Tally is 100
Tally is 100
Tally is 100
Tally is 100
Tally is 100
Tally is 100
0
Tally is 100
Tally is 100
当我希望最终输出为 1000 时。如何跨线程递增?
提前致谢。