我有以下情况:我在这里展示的代码很简单,以澄清我的担忧:
public void callMe()
{
AtomicInteger howManyOdds = new AtomicInteger(0);
AtomicInteger howManyEvens = new AtomicInteger(0);
loopThrough(100,howManyOdds,howManyEvens);
System.out.println(howManyOdds.get()+" "+howManyEvens.get());
}
private void loopThrough(int counter,AtomicInteger howManyOdds,AtomicInteger howManyEvens)
{
for(int i = 1 ; i <= counter ;i++)
{
if(i%2 == 0)
howManyEvens.getAndAdd(1);
else
howManyOdds.getAndAdd(1);
}
}
我知道它可以做到,int[]
但它看起来有点奇怪。在这种情况下,AtomicInteger 是 Mutable Integer 的良好替代品吗?如果否,那么为什么?