在自己的构造函数中调用thread.start() [英] calling thread.start() within its own constructor

查看:186
本文介绍了在自己的构造函数中调用thread.start()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个线程在它自己的构造函数中调用this.start()是否合法?如果是这样,这会导致什么潜在问题?我知道该对象在构造函数运行完成之前不会完全初始化,但除此之外还有其他问题吗?

is it legal for a thread to call this.start() inside its own constructor? and if so what potential issues can this cause? I understand that the object wont have fully initialized until the constructor has run to completion but aside from this are there any other issues?

推荐答案

出于内存安全原因,您不应该将对象或该对象的字段的引用从内部暴露给另一个线程它的构造函数。假设您的自定义线程具有实例变量,通过从构造函数中启动它,您可以保证违反Java内存模型准则。有关详细信息,请参见 Brian Goetz的安全施工技术

For memory-safety reasons, you shouldn't expose a reference to an object or that object's fields to another thread from within its constructor. Assuming that your custom thread has instance variables, by starting it from within the constructor, you are guaranteed to violate the Java Memory Model guidelines. See Brian Goetz's Safe Construction Techniques for more info.

这篇关于在自己的构造函数中调用thread.start()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆