我在问这个问题时有些尴尬,但是以下代码片段的结果使我感到困惑:

System.out.println("incrementResultResponses() has been invoked!");
final long oldValue = resultResponses;
final long newValue = resultResponses++;
System.out.println("Old value = " + oldValue);
System.out.println("New value = " + newValue);

输出以下内容:
incrementResultResponses() has been invoked!
Old value = 0
New value = 0

为什么?并发对这里的结果有影响吗?顺便说一句,resultResponseslong

最佳答案

后缀++运算符返回值(递增之前)。您想使用前缀++:

final long oldValue = resultResponses;
final long newValue = ++resultResponses;

10-07 22:48