gpt4 book ai didi

java - static int 在单线程中比 AtomicInteger 计数更多,为什么?

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:56 24 4
gpt4 key购买 nike

以下代码的输出是9123:9158

import java.util.concurrent.atomic.AtomicInteger;

public class StackOverflow {

private static AtomicInteger atomicInteger = new AtomicInteger(0);
private static int staticInt = 0;

public static void main(String args[]) {

int atomicInt = atomicInteger.incrementAndGet();

staticInt++;

try {
// recursive call to main() to get StackOverflowError
main(args);

} catch(StackOverflowError soe) {

System.out.println(atomicInt+":"+staticInt);
// staticInt gets more count, why so?
}
}
}

这会在 static intAtomicInteger 之间产生 35 的差异。我不确定为什么会这样,我有这些问题想得到答案。

在单线程上运行时,两者应该给出相同的计数,对吗?知道为什么这不是这样吗?

我们如何获得发生 StackOverflowError 所需的正确调用次数?

static contekt 中使用 AtomicInteger 是错误的吗?

最佳答案

这是因为你正在打印 atomicInt。如果您改为打印 atomicInteger,您将获得预期的结果。

每次调用 main 都有一个 atomicInt 变量,因此在您的示例中有 9000 多个这样的变量。

当你得到 StackOverflowError 时,执行以相反的顺序通过堆栈,直到 System.out.println 语句可以执行(它也可能抛出 SOE!),并且atomicInt 对应于特定的 main 调用小于 staticIntatomicInteger 的当前值。

换句话说,在您的示例中,抛出 34 个 StackoverflowError 并且第 35 次调用 System.out.println 成功,但是 atomicInt 的调用中mainstaticInt 的当前值小 35,因此是 9123 与 9158。

要查看它,您可以像这样修改您的程序:

private static int soeCount = 0;

//...

} catch (StackOverflowError soe) {
soeCount++;
System.out.println(atomicInt + ":" + staticInt + " -> " + soeCount);
// staticInt gets more count, why so?
}

您应该会看到 soeCount 大于 1(尽管不一定等于差值,因为 soeCount++ 可能不会在每个堆栈帧上执行。

关于java - static int 在单线程中比 AtomicInteger 计数更多,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21905931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com