gpt4 book ai didi

java - 以线程安全方式创建对象

转载 作者:搜寻专家 更新时间:2023-10-31 19:28:50 27 4
gpt4 key购买 nike

直接来自 this网站上,我看到了以下关于创建对象线程安全的描述。

Warning: When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the following line to your constructor:

instances.add(this);

But then other threads can use instances to access the object before construction of the object is complete.

是否有人能够用其他词或另一个更容易理解的例子来表达相同的概念?

提前致谢。

最佳答案

  1. 让我们假设,你有这样的类(class):

    class Sync {
    public Sync(List<Sync> list) {
    list.add(this);
    // switch
    // instance initialization code
    }

    public void bang() { }
    }
  2. 你有两个线程(线程 #1 和线程 #2),它们都有一个相同的引用 List<Sync> list实例。

  3. 现在线程 #1 创建一个新的 Sync实例并作为参数提供对 list 的引用实例:

    new Sync(list);
  4. 在执行行 // switch 时在Sync构造函数有一个上下文切换,现在线程 #2 正在工作。

  5. 线程 #2 执行这样的代码:

    for(Sync elem : list)
    elem.bang();
  6. 线程 #2 调用 bang()在第 3 点创建的实例上,但是这个实例还没有准备好使用,因为这个实例的构造函数还没有完成。

因此,

  • 在调用构造函数和传递对几个线程之间共享的对象的引用时必须非常小心
  • 在实现构造函数时,您必须牢记所提供的实例可以在几个线程之间共享

关于java - 以线程安全方式创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717962/

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