Search code examples
javamultithreadinginterrupt

Thread Interrupted sometimes works and sometimes not


Please help me with my problem. I have 2 JMenuItems, if I Click on Start it shall start and do stuff. If I click on Stop it shall stop :) After i clicked on Start, I click on Stop and sometimes it stops and sometimes not. But I want that it always stops.

What have I done wrong? :/

class DiashowListener implements ActionListener {
Thread td;
boolean ok = false;

        public void actionPerformed(ActionEvent e) {

            if (e.getActionCommand().equals("Start")) { 

                td = new Thread(new Runnable() {
                    public void run() {
                        if (bimg != null) {
                                while (!ok) {
                                    try {
                                        ...


                                     } catch (Exception e2) {
                                    }   
                                    frame.repaint();
                                }                       
                        } 
                    }
                });

                td.start();

            } else if (e.getActionCommand().equals("Stop")) {
                if (td != null){
                    ok = true;
                }
            }
        }
}

EDIT: ok I changed something, its working now, but: If I click on Stop it shall stop immediately.


Solution

  • First of all, you are interrupting the wrong thread (should be td). Second, the contents of the try clause that you omitted is actually important (some operations are uninterruptible). Finally, Thread.isInterrupted is likely not what you want to use, as the flag may get cleared by some unrelated code. Depending on what exactly you are interrupting, it may (or may not) be a good idea to just catch InterruptedException, and terminate in case it is thrown. A better approach is to add your own flag, that the thread will check instead of isInterrupted, and the event handler will set instead of (or in addition to) interrupting the worker thread.