java - 在构造函数中启动线程

标签 java concurrency

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/

相关文章:

java - 使用随机类填充数组,然后打印它的值

java - 如何管理默认的 Java SwingWorker 线程池?

java - 测试多线程代码或确保代码是线程安全的指南

c++ - 发布者和消费者线程之间通过堆栈共享数据

java - Maven 编译错误。执行javac失败,但无法解析错误:javac: invalid flag: -s

java - 使用 Spring RestTemplate 将嵌套的 JSON 对象映射到 Java 类

java - 字符串分词器问题

java - 使用原子变量在 Java 中实现互斥量

java - 如何使用 volatile 变量编写简单的线程安全类?

concurrency - 如果只有很少的进程可以并行执行,那么能够有效地生成数十个进程有什么意义呢?