How to terminate or kill a thread entirely in java?

Question:

At the time of initializing a new Thread, after the run() method is executed completely, how can I kill 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
}

just like this

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 components of the frame 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's because the threads are running, because by removing the method thread and leaving only the process code, the program runs great.

Answer:

You cannot command the execution of a thread to terminate. The only thing you can do is make sure that the execution of the run method (by implementing Runnable or by extending Thread ) has some way of ending. 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 kill thread execution):

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 recommended to create Thread s directly and modify the frames from there since Swing uses a different thread for the administration of 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