大家好!
我有一个更新观察者模式视图的线程。更新运行良好,但问题是中断不起作用。请帮忙。
主:
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();
}
答案 0 :(得分:4)
当Thread.sleep()
抛出InterruptedException
时,您的interrupted
线程标志设置为false
(请参阅JavaDoc以获取Thread.sleep()
),因此您需要在interrupt()
条款中添加break
或catch
。