0

I have code like below. I have the following problem: I must stop Thread t, but inside is a method which suspends the thread in one place for long time. So when I'm trying to stop it, it stops after that method is executed. Anyone know how to terminate this thread or stop it in any other way while executing the method inside the thread?

public class MyClass extends JFrame implements Runnable{       
    @Override
    public void run() {   
        OtherClass oc = new OtherClass();
        Runnable r = oc;
        Thread t = new Thread(r);
        t.start();

        addButton(buttonPanel, "Stop it", new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                System.out.println("stopping");
                t.stop();                      
                setVisible(false);                
            }
        }); 
    }
}    

public void addButton(Container c, String title, ActionListener listener) {
    JButton button = new JButton(title);
    c.add(button);
    button.addActionListener(listener);
}
VLS
  • 2,306
  • 4
  • 22
  • 17
Matt
  • 1
  • 2
    Where is the thread waiting? Also, never use `Thread.stop()`. – shmosel Aug 12 '16 at 18:32
  • 1
    I'm not a Swing expert, but `extends JFrame implements Runnable` sounds like a recipe for trouble. Why `implements Runnable`? Where is that `run()` method called from? – Solomon Slow Aug 12 '16 at 18:32
  • See [Thread.interrupt()](https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html) – copeg Aug 12 '16 at 18:35
  • `run` method is called from other class. It's not complete listing. – Matt Aug 12 '16 at 18:37
  • You should use `Thread.interrupt()`, as mentioned. If you're doing a lot of looping inside that thread, periodically call `Thread.interrupted()` to check if a stop has been requested. – markspace Aug 12 '16 at 18:39
  • @markspace i cant do this, becouse inside thread i have method call which pause it for long time (making calculations) – Matt Aug 12 '16 at 18:41
  • 2
    This method would definitely have a loop, use this loop to check for `Thread.interrupted()` or use a volatile boolean variable which is set on click of stop button. – 11thdimension Aug 12 '16 at 18:45
  • I don't know what is inside, because its compiled code. – Matt Aug 12 '16 at 18:52

0 Answers0