并发代码中赋值运算符的返回值 [英] Return value of assignment operator in concurrent code

查看:144
本文介绍了并发代码中赋值运算符的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下类:

class Foo {
  public volatile int number;

  public int method1() {
    int ret = number = 1;
    return ret;
  }

  public int method2() {
    int ret = number = 2;
    return ret;
  }
}

在同一个 Foo 实例上同时使用方法1()和 method2()

and given multiple threads calling method1() and method2() concurrently on the same Foo instance, can a call to method1() ever return anything other than 1?

推荐答案

JLS 15.26规定:

The JLS 15.26 specifies:


有12个赋值运算符;所有都是语法右相关的(他们从右到左)。因此,a = b = c表示a =(b = c),它将c的值赋给b,然后将b的值赋给a。

There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

Ted Hopp的回答表明Sun的javac不会遵循这个行为,可能是一个优化。

Ted Hopp's answer shows that Sun's javac doesn't follow this behaviour, possibly as an optimisation.

由于这里的线程,行为method1将是未定义的。如果Sun的编译器使得行为常数,那么它不会从未定义的行为中断。

Due to the threading here, the behaviour of method1 would be undefined. If Sun's compiler makes the behaviour constant then it doesn't break from the undefined behaviour.

这篇关于并发代码中赋值运算符的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆