I'm very new into Threads and I'm facing following problem when using a thread in my code.
On a button click I'm starting a thread which runs a specific task, and this task is running in the background of the system. I am using a while loop inside the thread to check if a volatile bool is changed by another button click to stop the whole process. The problem is I have to add an empty loop else it looks like the thread stops itself and does not check for the while condition anymore. I assume this is very inefficient and wastes a lot of ressources.
I'm adding a shorted version of the code to make it less unreadable.
Any idea why this happens and how I could improve the overall efficiency of my code?
public void onClick(View view) {
new Thread(new Runnable() {
public void run() {
//execute my task
while(!stopThread) {
// Without this empty loop the thread stops after a while
}
while(stopThread) { // stopThread is a volatile bool changed by another button click
//Finish the task
break;
}
}
}).start();
}