大家好!

我有一个线程可以更新“观察者模式”的 View 。更新工作正常,但问题是中断无法正常工作。请帮忙。

主要的:

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();
}

最佳答案

Thread.sleep()抛出InterruptedException时,您的interrupted线程标志被设置为false(有关Thread.sleep()的信息,请参阅JavaDoc),因此您需要在interrupt()子句中添加breakcatch

10-06 16:18