Kill a thread on Android onBackPressed ()

3

I am trying to kill this thread as soon as I press the back button. But in "HiloConsumo" it does not pick up the reference of the thread

        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.
    }
}
    
asked by Eduardo 17.05.2017 в 21:51
source

1 answer

2

This would be the correct way to interrupt the execution of a Thread :

You create the Thread:

Thread myThread = new Thread("ThreadEduardo");

in this way valid if it exists and you proceed to stop its execution.

  if(myThread != null){  //valida si existe.
      myThread.interrupt();  //Interrumpe su ejecución.          
  }

The stop () method is not used because it is obsolete.

  

stop () This method was obsolete in API level 1. This method is inherently insecure. Stopping a thread with Thread.stop makes   unlock all the monitors you have blocked (such as a   natural consequence of the unverified ThreadDeath exception that   propagates in the pile).

This is an example for you to see the operation of the Thread and its interruption.

You declare a variable type Thread :

private Thread HiloConsumo;
private static final String TAG = "MainActivity";

Create a class that extends from Thread:

 private class MyThread extends Thread {
        @Override
        public void run(){
            while(true) {
                Log.d(TAG, "En ejecucion: " + HiloConsumo.getName() + " | " + System.currentTimeMillis());
                try {
                    sleep(1000); //pausa un segundo.
                } catch (InterruptedException e) {
                    Log.e(TAG, "Error " + e.getMessage());
                }
            }
        }
    }

You would create your Thread in this way:

  HiloConsumo = new MyThread(); //crea instancia.
  HiloConsumo.setName("Hilo Eduardo"); //Asigna nombre.
  HiloConsumo.start(); //inicia Thread.

By calling onBackPressed () you can see that the execution is interrupted:

  public void onBackPressed() {
        if (HiloConsumo != null)//valida si existe instancia de Thread.
        {
            Log.d(TAG, "interrumpe Thread!" + HiloConsumo.getName());
            HiloConsumo.interrupt();  //Interrumpe su ejecución.
        }
    }
    
answered by 17.05.2017 / 21:57
source