1

The following thread runs on a button click.

open.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        calls();
    }
});


private void calls() {
    Thread t = new Thread(this);
    t.start();
}

@Override
public void run() {
    reads();
}

public void reads() {
    ....
    ....
    counter++;
    // The Thread should stop here right>
}

But it doesn't end there. I am using thread.stop() to stop the thread there. I know the range the counter has to go. I display counter value in UI. If I click the open button once the counter reaches the end state, then it shows an Interrupted exception.

Joker
  • 81
  • 12
  • See http://stackoverflow.com/questions/1283328/are-thread-stop-and-friends-ever-safe-in-java – Raedwald Mar 20 '14 at 13:08
  • This threads are action performed on the main thread. –  Mar 20 '14 at 13:14
  • 1
    I don't know why there is a down vote here. I have seen the topic you have suggested. I posted the question here because I couldn't understand that. I know stop() method is deprecated but it is the only way my thread stops else it shows exception when I click open button again – Joker Mar 20 '14 at 13:14
  • I'm not sure I understand you correctly. If you have a `Thread.currentThread().stop()` in your method `reads()`, why did you remove it? That's the kind of thing you need to show. And where do you get this InterruptedException? – Erwin Bolwidt Mar 20 '14 at 13:15
  • If I click the open button again I get InterruptedException. I don't know how but now it works properly. – Joker Mar 20 '14 at 13:17

1 Answers1

1

Define your t object outside the function, maybe in the constructor. Then you can stop it with this:

 t.interrupt();

EDIT

Thread t;
public myclass()//your constructor
{
t=new Thread(this);
}

    open.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            calls();
        }
    });


    private void calls() {
        t.start();
    }

    @Override
    public void run() {
        reads();
    }

    public void reads() {
        ....
        ....
        counter++;
t.interrupt();// The Thread should stop here right>

    }
AloneInTheDark
  • 938
  • 4
  • 15
  • 36
  • 1
    Thanks for the help but it works fine now and I don't have any idea this works. – Joker Mar 20 '14 at 13:21
  • You're welcome. Use t.interrupt instead of t.stop when you want to stop your thread. Because it's not safe. – AloneInTheDark Mar 20 '14 at 13:26
  • Why would you want to interrupt your own thread from within in its run method? reads() is called from run(). Origianl question : seems to be worked out some other way per Parthe comment but am sure interrupt did not help – tgkprog Mar 20 '14 at 14:00