以线程安全的方式创建对象

以线程安全的方式创建对象

本文介绍了以线程安全的方式创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直接从网站,我遇到了有关创建对象的以下描述线程安全。

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



提前感谢。

解决方案

  1. 让我们假设你有这样的类:

      class Sync {
    public Sync(List< Sync> list){
    list.add(this);
    // switch
    //实例初始化代码
    }

    public void bang(){}
    }


  2. 并且你有两个线程(线程#1和线程#2),它们都有一个引用 List< Sync>现在线程#1创建了一个新的同步实例。

  3. 作为参数提供对列表实例的引用:

      new同步(列表); 


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


  5. #2执行此类代码:

      for(Sync elem:list)
    elem.bang


  6. 线程#2调用 bang()在第3点创建的实例上,但此实例尚未准备好使用,因为此实例的构造函数尚未完成。


因此,在调用构造函数时,必须非常小心,





  • 。您必须记住,提供的实例可以在几个线程之间共享


Directly from this web site, I came across the following description about creating object thread safety.

Is anybody able to express the same concept with other words or another more graspable example?

Thanks in advance.

解决方案
  1. Let us assume, you have such class:

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

  2. and you have two threads (thread #1 and thread #2), both of them have a reference the same List<Sync> list instance.

  3. Now thread #1 creates a new Sync instance and as an argument provides a reference to the list instance:

    new Sync(list);
    

  4. While executing line // switch in the Sync constructor there is a context switch and now thread #2 is working.

  5. Thread #2 executes such code:

    for(Sync elem : list)
        elem.bang();
    

  6. Thread #2 calls bang() on the instance created in point 3, but this instance is not ready to be used yet, because the constructor of this instance has not been finished.

Therefore,

  • you have to be very careful when calling a constructor and passing a reference to the object shared between a few threads
  • when implementing a constructor you have to keep in mind that the provided instance can be shared between a few threads

这篇关于以线程安全的方式创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:05