(可能很奇怪)长增量行为?
我问这个问题有点尴尬,但以下代码片段的结果让我难住了:
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
为什么?并发会对这里的结果产生任何影响吗?顺便说一句,resultResponses
是一个long
。
I'm a bit embarrassed in asking this question, but the result of the following code snippet has me stumped:
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);
That outputs the following:
incrementResultResponses() has been invoked!
Old value = 0
New value = 0
Why? Would concurrency have any influence upon the result here? By the way, resultResponses
is a long
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
后缀
++
运算符返回旧值(递增之前)。您想使用前缀++
:The postfix
++
operator returns the old value (before incrementing). You want to use prefix++
:因为增量会在分配后增加值(后增量)。这正是
resultResponses++
应该做的事情。如果希望resultResponses为1,则需要使用Pre-Increment,即
++resultResponses
Because the increment increases the value after it was assigned (Post-Increment). That's exactly what
resultResponses++
is supposed to do.If you want resultResponses to be 1, you need to use Pre-Increment, which is
++resultResponses
如果您想在赋值之前递增 oldValue,则必须在变量之前放置
++
:这意味着递增发生在语句执行之前而不是之后。
If you want to increment oldValue before the assignment you will have to place
++
before the variable:This means that the increment takes place before the statement is executed instead of after.
请参阅 此,了解如何
postfix
和prefix
有效。正如上面的答案中提到的,您可以使用这个:
或者为了让它更漂亮,您也可以使用:
这也会产生相同的输出。
Refer this, to know how
postfix
andprefix
work.As mentioned in the above answers you can use this:
Or to make it fancier you can also use:
which will also result in the same output.