Hi I'm trying to stop a thread while running I know the thread should cooperate so it can be stopped I used a boolean variable but the thread keeps running. is there any way to stop a thread while it's running? Or can I start and stop a thread with the same button?
boolean boolean_variable = true;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (boolean_variable) {
for (int i = 0; i < 100; i++) {
System.out.println("thread running " + i);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
//start the thread
buttonOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
thread.start();
}
});
//stop the thread
buttonTwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean_variable = false;
}
});