Save the boolean cancelled flag to keep the status. Initialize it to false, and then change it to true by clicking the Stop button.
And inside your run() method, keep checking this flag.
Edit
The approach usually works, but still not the most suitable way to stop runnable / thread. There may be a situation where the task is locked and cannot check the flag, as shown below:
public void run(){ while(!cancelled){
Suppose the task makes a blocking api call and then the flag is canceled. The task will not be able to check the status change until an API lock call is made.
Alternative and safe approach
The most reliable way to stop a thread or task (Runnable) is to use an interrupt mechanism. Interruption is a collaboration mechanism to ensure that stopping a thread does not leave it in an inconsistent state.
On my blog, I discussed in detail the interrupt link .
source share