登陆

java - 请问我的这个线程要怎么停掉?

因为是另外一个窗口调用了次类,所以使用JFrame.DISPOSE_ON_CLOSE以免把其他窗口都关了。但是退出的时候并没有把另外一个线程关掉。

public class ABC extends JFrame implements Runnable {
    public static void main(String[] args) {
        ABC abc= new ABC();
    }
    
    public ABC(){
        Thread thread = new Thread(this);    //此处的线程还在运行
        thread.start();
        
        this.setSize(600,430);
        this.setResizable(false);//固定窗体大小
        this.setLocationRelativeTo(null);//打开时相对window居中
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);    //此处会导致退出窗口后线程还在运行
        this.setVisible(true);
    }
    
    @Override
    public void run() {
        while (true){
            System.out.println("ABC");
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
# Java
小葫芦小葫芦1652 天前257 次浏览

全部回复(1)我要回复

  • 黄舟

    黄舟2017-04-17 17:28:28

    做个开关。
    比如在while上做个变量判断,窗口退出时修改该变量,使while结束。

    回复
    0
  • 取消回复发送