在 Brian Goetz's article about safe construction techniques你可以阅读:
[...] often when an object owns a thread, either that thread is an inner class or we pass the this reference to its constructor (or the class itself extends the Thread class). If an object is going to own a thread, it is best if the object provides a start() method, just like Thread does, and starts the thread from the start() method instead of from the constructor. While this does expose some implementation details (such as the possible existence of an owned thread) of the class via the interface, which is often not desirable, in this case the risks of starting the thread from the constructor outweigh the benefit of implementation hiding.
我想使用下面的代码应该不会有任何问题。因为它不是内部类,所以我也没有传递 this
的引用。但我想确定一下。
private Controller controller;
private View view;
public Facade() {
view = new View();
controller = new Controller(view);
controller.start();
}
不过,我不断收到 NetBeans 警告...那么这段代码安全还是不安全?
最佳答案
主要原因是不在构造函数中启动线程 - 在创建“this”之前(在构造函数执行之后)不要公开“this”。在您的代码中我没有看到这样的代码:
new Thread(this);
所以应该没问题。
关于java - 在构造函数中启动线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10945520/