是否真的可以在构造函数中创建的线程中查看部分构造的对象,因为缺少同步和泄漏此实例?
当然,除了有子类的情况,或者我们正在使用clone或类似的东西进行隐式构造 – 所以让我们假设该类是final,并且在调用其他线程之前调用构造函数的线程中它是完全初始化的.
据我所知,以下hb()规则适用,
>线程中的每个操作都发生在该线程中的每个操作之前
稍后在程序订单(程序订单规则)中出现
>在启动线程中的任何操作之前,对线程的start()调用发生.
>如果是hb(x,y)和hb(y,z),则为hb(x,z)
所以它是否意味着以下代码在技术上是线程安全的(我从类似的问题Why shouldn’t I use Thread.start() in the constructor of my class?中得到它,也有一个类似的问题Why it is bad practice to create a new thread on constructors?,p.s.我希望这个不会被关闭作为重复)
final class SomeClass
{
public ImportantData data = null;
public Thread t = null;
public SomeClass(ImportantData d)
{
t = new MyOperationThread();
// t.start(); // Footnote 1
data = d;
t.start(); // Footnote 2
}
}
附:显然数据字段在这里缺乏封装,但是这个问题是关于对象从线程t的状态可见性.
解决方法
是的,它确实.规格明确
writes:
An action that starts a thread synchronizes-with the first action in the thread it starts.
当然,当构造函数完成时,不保证对象完全初始化,因为构造函数可以调用其他构造函数 – 通过explicit constructor invocation statement,或者因为隐式调用了超类默认构造函数.因此,从构造函数中泄漏它是相当脆弱的 – 具有单个或多个线程.