java – 在程序命令规则在构造函数中工作之前发生了吗?

是否真的可以在构造函数中创建的线程中查看部分构造的对象,因为缺少同步和泄漏此实例?

当然,除了有子类的情况,或者我们正在使用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,或者因为隐式调用了超类认构造函数.因此,从构造函数中泄漏它是相当脆弱的 – 具有单个或多个线程.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...