简体   繁体   English

Java:在构造函数中启动一个新线程

[英]Java: starting a new thread in a constructor

Why is starting a new thread in a constructor frowned upon in Java (or anywhere, for that matter). 为什么在Java中(或者就任何地方而言)在构造函数中开始一个新线程。 I'm getting warnings from Netbeans for doing so, but it isn't giving me any refactoring suggestions. 我收到了Netbeans的警告,但它没有给我任何重构建议。 I'm writing a client/server Swing application, and the thread I'm starting is in the server's JFrame constructor, in order to continuously listen for client datagrams. 我正在编写一个客户端/服务器Swing应用程序,我正在启动的线程是在服务器的JFrame构造函数中,以便持续监听客户端数据报。

Why is this not good practice and how should I avoid it? 为什么这不是好的做法,我应该如何避免呢?

Starting a thread from the constructor lets the started thread access the object being constructed before it's properly constructed, and thus makes a not completely constructed object available to the new thread. 从构造函数启动一个线程允许启动的线程在正确构造之前访问正在构造的对象,从而使新线程可以使用一个未完全构造的对象。

You could create the thread in the constructor, and provide a "startup" method to start the thread from the outside. 您可以在构造函数中创建线程,并提供“启动”方法以从外部启动线程。

Or you could make the constructor and startup methods private and provide a static factory method which would create the object, start the thread, and return the created object. 或者,您可以将构造函数和启动方法设置为私有,并提供静态工厂方法,该方法将创建对象,启动线程并返回创建的对象。

Have a look at this link http://www.ibm.com/developerworks/java/library/j-jtp0618/index.html#code4 请访问此链接http://www.ibm.com/developerworks/java/library/j-jtp0618/index.html#code4

This is do with implicit references to this and subclassing . 这与thissubclassing隐式引用有关。

使类最终,也可以是一个解决方案,因为没有子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM