I have a thread which contains an infinite loop. I have a UI which has start and stop buttons. When I click start, the thread should run and when I click stop, the thread should stop. The model of code is as given below
In this code, if I click stop button and then again click start button, IllegalThreadStateException occurs on t.start() line. This means the thread has not yet stopped but I want the thread to stop. How can this be solved?
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
--- Martin Fowler
Thanks for your reply. I know that IllegalThreadStateException occurs if we start a thread that is running. I want to know how to stop it on click of stop button. t.stop() or t.interrupt() aren't working.
As you see I have a controlling variable for the while() loop. If the thread runs continuously, I can use the variable to start and stop but I fetched a value at the start of the thread which becomes null if I continuously run the thread.
You seem to misunderstand what the word "stop" means when applied to a Thread. It means that the code in the Thread's run() method terminates and the Thread can no longer be used. Likewise you're misusing "start" -- that means that the code in the Thread's run() method starts at the beginning. As already mentioned, you can only start a Thread once.
If I'm not mistaken you want to pause the Thread's operation, i.e. for it to cease what it's doing in that infinite loop. And then later you want to resume that processing.
I don't know why you aren't using a Timer to do this repetitive processing, but if you really need to use a low-level tool like Thread for this then your code should look something like this:
where paused is a boolean variable which you set on to pause and off to resume.