Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }

}

View (interrupt button):

private void bt_stopActionPerformed(java.awt.event.ActionEvent evt) {                                        
     Main.t.interrupt();
} 
like image 592
user547995 Avatar asked May 24 '26 07:05

user547995


1 Answers

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.

like image 57
Alex Abdugafarov Avatar answered May 26 '26 19:05

Alex Abdugafarov