Can语句n!= n在多线程环境中返回true [英] Can statement n != n returns true in multithread environment

查看:214
本文介绍了Can语句n!= n在多线程环境中返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何模拟构造函数竞争条件?

如何证明未正确发布的值的竞争条件?

我从实际中的java并发中得到以下代码:

I got the following code from 《java concurrency in practice》:

public class Holder{

  private int n;
  public Holder(int n){this.n = n;}
  public void assertSanity(){
     if(n != n) throw new AssertionError("This statement is false.");

  }


}

我只是想知道条件 n!= n ,在某种情况下这可能是真的吗?

I am just wondering the condition n != n, is this could be true under a certain circumstance?

推荐答案

我的猜测是你在问这些类似的问题:

My guess is that you are asking something similar to these questions:

  • How to demonstrate race conditions around values that aren't published properly?
  • How to simulate constructor race conditions?

我猜这本书正在讨论在完全对象之前共享引用的可能性构建,提到的行为是不正当的发布。

I'm guessing the book is talking about the possibility of sharing a reference to an object before it is completely constructed, an act referred to is improper publishing.

假设 n!= n 被分解为以下内容小号teps:

Suppose that n != n is broken down into the following steps:

Access n on the right side of the operand
Access n on the left side of the operand
Compare values

然后就可以想象一个案例中的价值 n 在前两个步骤之间更改。现在我知道你在想什么,但 n 永远不会改变。实际上,因为两个线程可以在该实例的构造函数完全运行之前共享对 Holder 实例的访问。

Then it follows that it is not hard to imagine a case in which the value of n is changed between the first two steps. Now I know what you are thinking, "but n is never changed". Actually, it is, because two threads could share access to an instance of Holder before the constructor for that instance has completely run.

这篇关于Can语句n!= n在多线程环境中返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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