I'm trying to kill this thread as soon as I hit the back button. But in "HiloConsumo" it does not pick up the thread reference well
new Thread("HiloConsumo") {
public void run() {
while (true) {
System.out.println("----------------------------------");
// stock.print();
} catch (Exception ex) {
}
}
}
}.start();
}
public void onBackPressed() {
if (HiloConsumo != null)//valida si existe.
{
HiloConsumo.interrupt(); //Interrumpe su ejecución.
}
}
This would be the correct way to interrupt the execution of a Thread :
You create the Thread:
in this way you validate if it exists and proceed to stop its execution.
The stop() method is not used as it is deprecated.
This is an example for you to see the operation of the Thread and its interruption.
You declare a type variable
Thread
:Create a class that extends Thread:
You would create your Thread like this:
when calling onBackPressed() you can see that the execution is interrupted: