本文介绍了Java:在构造函数中启动一个新线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在Java中(或者就任何地方而言)在构造函数中开始一个新线程。我收到了Netbeans的警告,但它没有给我任何重构建议。我正在编写一个客户端/服务器Swing应用程序,我正在启动的线程在服务器的JFrame构造函数中,以便持续监听客户端数据报。

Why is starting a new thread in a constructor frowned upon in Java (or anywhere, for that matter). I'm getting warnings from Netbeans for doing so, but it isn't giving me any refactoring suggestions. 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.

为什么这是不好的做法,我该如何避免呢?

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.

这篇关于Java:在构造函数中启动一个新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:09