问题描述
直接从网站,我遇到了有关创建对象的以下描述线程安全。
是否有人能够用其他词语或另一个更容易理解的例子来表达相同的概念?
提前感谢。
-
让我们假设你有这样的类:
class Sync {
public Sync(List< Sync> list){
list.add(this);
// switch
//实例初始化代码
}
public void bang(){}
}
-
并且你有两个线程(线程#1和线程#2),它们都有一个引用
List< Sync>现在线程#1创建了一个新的
同步
实例。 作为参数提供对 -
执行行
// switch
Sync 构造函数中有一个上下文切换,现在线程#2正在工作。 -
#2执行此类代码:
for(Sync elem:list)
elem.bang
-
线程#2调用
bang()
在第3点创建的实例上,但此实例尚未准备好使用,因为此实例的构造函数尚未完成。
列表
实例的引用: new同步(列表);
因此,在调用构造函数时,必须非常小心,
- 。您必须记住,提供的实例可以在几个线程之间共享
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.
Let us assume, you have such class:
class Sync { public Sync(List<Sync> list) { list.add(this); // switch // instance initialization code } public void bang() { } }
and you have two threads (thread #1 and thread #2), both of them have a reference the same
List<Sync> list
instance.Now thread #1 creates a new
Sync
instance and as an argument provides a reference to thelist
instance:new Sync(list);
While executing line
// switch
in theSync
constructor there is a context switch and now thread #2 is working.Thread #2 executes such code:
for(Sync elem : list) elem.bang();
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
这篇关于以线程安全的方式创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!