How can I kill a Thread

Asked

Viewed 543 times

0

I’d like to know how to kill a Thread.

public class thread {

    private static void metodo(){
        new Thread(){
            @Override
            public void run(){
                while(true){
                    System.out.println("Executando...");
                    try {
                        Thread.sleep(2000);
                        Thread.interrupted();
                    } catch (InterruptedException ex) {
                        System.out.println("Interrompido!");
                        break;
                    }
                }
            }
        }.start();
    }

    public static void main(String[] args) {
        metodo();
    }

}

I would not like to break into While, I would like to kill Thread with her own methods.

I have an application that needs to stop a Thread to run it again, without running the same method in parallel, for this reason my doubt.

  • 1
  • 1

    I think it is easier to check if the thread is over than to kill it. Until, when the thread ends after this break, there is no more action to be taken.

  • Or you can use the method interrupt()

  • I get it, so it’s better to finish it than to kill it, I’ll review my method in my application and I’ll give you a feedback, thank you.

  • I was able to solve it, I checked my Thread and it was finished, but when I called the method that restarted it, it ended up looping, thank you very much for the information. @Articuno

1 answer

1


Thread doesn’t kill itself, it has to stop on its own, so you don’t escape using a signal or flag mechanism.

  • I understand, it has to end on its own, thank you for the short and objective answer.

  • 1

    Exactly, EVEN IF THERE IS A WAY to kill a thread, as Posix threads has, it is never advisable to use, because it will surely be things in half, memory not released, etc. Threads are dangerous enough without it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.