首页  

Java为什么不能在构造函数中启动线程?如何终止一个线程?     所属分类 java 浏览量 679
public class MyNewThread implements Runnable {
    Thread t;
    MyNewThread() {
        t = new Thread (this, "MyNewThread");
        t.start();
    }

    public void run()  {
        // ...
    }
...
}

public class Main {
    public static void main(String[] args) throws Exception{
        new MyNewThread();
        //  
    }  
}

编译器警告 在构造函数中启动线程很危险

在构造函数中启动一个线程,并传递this
在完全构造对象之前给出对对象的引用
该线程将在构造函数完成之前启动,这会导致各种奇怪的行为

Java中没有强制停止线程的方法,可以使用 状态变量来控制

public class MyNewThread implements Runnable {

    private final Thread t;
    private volatile boolean stop = false;

    MyNewThread() {
        t = new Thread (this, "MyNewThread");
    }

    public void start() {
        t.start();
    }

    public void stop() {   
         stop = true;
    }

    public void run()  {
         while(true){
            if(stop){
                return;
            }
         }
    }
}

上一篇     下一篇
GO基础选择题

MySQL timestamp 类型

mysql 时间类型

ETF IOPV 实时净值参考

GO为什么没有虚拟机

Rust语言设计理念及优缺点