在Java中打断无尽线程的问题

时间:2011-04-17 12:01:34

标签: java multithreading

大家好!

我有一个更新观察者模式视图的线程。更新运行良好,但问题是中断不起作用。请帮忙。

主:

public class Main {

    public static Sensor s;
    public static Thread t;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        s = new Sensor (1);
         t = new Thread(){

            @Override
            public void run() {

                Random r = new Random ();
               while (!isInterrupted())
               {
                    try {
                       s.setTemp(r.nextInt(40));

                        s.notifyObservers(s.getTemp());
                       sleep(500);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
               }


            }

        };
       JFrame jf = new JFrame();
       jf.setVisible(true);
       s.addObserver(jf);
       t.start();

    }

}

查看(中断按钮):

private void bt_stopActionPerformed(java.awt.event.ActionEvent evt) {                                        
     Main.t.interrupt();
} 

1 个答案:

答案 0 :(得分:4)

Thread.sleep()抛出InterruptedException时,您的interrupted线程标志设置为false(请参阅JavaDoc以获取Thread.sleep()),因此您需要在interrupt()条款中添加breakcatch