How to terminate or delete a thread completely in java?

Question:

When initializing a new Thread, after the run() method is fully executed, how can I remove this thread?

public void iniciarHilo(){
    new Thread(new Runnable() {

        public void run() {
            //Codigo 
        }
    }).start();

    //Una vez ejecutado el código del método run, necesito eliminar el hilo, o detenerlo
}

Same this way

public void iniciarHilo(){

    Thread hilo = new Thread(new Runnable() {

        public void run() {
            //Código 
        }
    });
    hilo.start();
    //Eliminar este hilo

}

What happens is that every time a specific decision is fulfilled, I call a method that starts a new thread within it, to eliminate frame components with a small delay between each one and that it looks good, but the more I fall into that decision, the program gets stuck.

I think it is because the threads remain running, because by removing the thread from the method and just leaving the process code, the program is doing great.

Answer:

You cannot command to terminate the execution of a thread. The only thing you can do is make sure that the execution of the run method (by implementing Runnable or extending from Thread ) has some way to finish. Upon completion of the execution of this method, the thread will terminate its execution. This is, instead of having something like

@Override
public void run() {
    while(true) {
        //tarea infinita que nunca va a terminar...
    }
}

At least have something like (this is actually too basic and not suitable for real world applications, but it illustrates a way to stop and terminate the execution of the thread):

volatile boolean ejecutar = true;

@Override
public void run() {
    while(ejecutar) {
        //tarea infinita que nunca va a terminar...
    }
}

public void detener() {
    ejecutar = false;
}

Since you mention the use of frames, I inform you that it is not advisable to create Thread s directly and modify the frames from there since Swing uses a different thread to manage the visual components. The best thing would be to use SwingWorker , but for a better detail we would need to know more about your particular case.


Forget the use of the Thread#stop and Thread#suspend . The official documentation clearly explains that you should not use these methods (check the content of the links provided). There is even an article dedicated to this: Why are Thread.stop , Thread.suspend and Thread.resume Deprecated? which translated means Why are the Thread.stop , Thread.suspend and Thread.resume methods deprecated? .

Scroll to Top