Problem to interrupt a endless thread in Java
Hy everyone!
I have a Thread who updates a view over the Observer Pattern. The update is working well, but the problem is that the interrupt doesn't work. Please help.
Main:
public cl开发者_运维知识库ass 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();
}
}
View (interrupt button):
private void bt_stopActionPerformed(java.awt.event.ActionEvent evt) {
Main.t.interrupt();
}
When Thread.sleep()
throws an InterruptedException
, your interrupted
thread flag is set to false
(refer to JavaDoc for Thread.sleep()
for that), so you need to add interrupt()
or break
in your catch
clause.
精彩评论