无法停止线程

Moo*_*ors 0 java

这是我正在使用的代码.

public class timerApp {
Runnable timerRun = new runX();
Thread thread1 = new Thread(timerRun);
public static void main(String[] args) {
    timerApp xyz = new timerApp();
    xyz.createGUI();
}
public void createGUI() {
    JButton button = new JButton("Start timer");
    JButton button2 = new JButton("Stop timer");
    JFrame frame = new JFrame();
    JLabel label = new JLabel("under_construction");
    frame.getContentPane().add(BorderLayout.NORTH,button);
    frame.getContentPane().add(BorderLayout.SOUTH,button2);
    frame.getContentPane().add(BorderLayout.CENTER,label);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,500);
    frame.setVisible(true);
    button.addActionListener(new b1L());
    button2.addActionListener(new b2L());
}
public class b1L implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        thread1.start();
    }
}
public class b2L implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        thread1.stop();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,Note: timerApp.java uses or overrides a deprecated API. Note: Recompile with Xlint:deprecation for details. 我在添加停止按钮的监听器类后开始得到这个错误.

RELP!

Bri*_*new 6

stop()确实被弃用了.它会使程序处于不一致状态.更好的方法是:

  1. Thread.interrupt()
  2. 在线程中设置一个boolean,并让该线程定期检查该变量

有关如何安全停止线程的详细信息,请参见此处.

  • +1表示使用什么而不是`thread.stop()` (2认同)

Joe*_*oey 5

首先,这不是错误.这是一个警告,您正在使用已弃用的方法.

Thread.stop()已弃用.你可以在这里阅读这背后的理由.

基本上他们的论点是没有安全的方法从外部终止线程; 因此,你应该使用的唯一方法是礼貌地要求线程停止:

我应该使用什么而不是Thread.stop?

stop的大多数用法应该由代码修改,该代码只是修改某个变量以指示目标线程应该停止运行.目标线程应该定期检查此变量,并且如果变量指示它将停止运行,则以有序的方式从其run方法返回.(这是JavaSoft教程一直推荐的方法.)为了确保快速通信停止请求,变量必须是易失性的(或者必须同步对变量的访问).

例如,假设您的applet包含以下start,stop和run方法:

private Thread blinker;

public void start() {
    blinker = new Thread(this);
    blinker.start();
}

public void stop() {
    blinker.stop();  // UNSAFE!
}

public void run() {
    Thread thisThread = Thread.currentThread();
    while (true) {
        try {
            thisThread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过将applet的stop和run方法替换为以下内容来避免使用Thread.stop:

private volatile Thread blinker;

public void stop() {
    blinker = null;
}

public void run() {
    Thread thisThread = Thread.currentThread();
    while (blinker == thisThread) {
        try {
            thisThread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}
Run Code Online (Sandbox Code Playgroud)