How do you kill a Thread in Java?

2018-12-31 01:16发布

How do you kill a java.lang.Thread in Java?

14条回答
荒废的爱情
2楼-- · 2018-12-31 01:33

One way is by setting a class variable and using it as a sentinel.

Class Outer {
    public static volatile flag = true;

    Outer() {
        new Test().start();
    }
    class Test extends Thread {

        public void run() {
            while (Outer.flag) {
                //do stuff here
            }
        }
    }

}

Set an external class variable, i.e. flag = true in the above example. Set it to false to 'kill' the thread.

查看更多
步步皆殇っ
3楼-- · 2018-12-31 01:35

I'd vote for Thread.stop().

As for instance you have a long lasting operation (like a network request). Supposedly you are waiting for a response, but it can take time and the user navigated to other UI. This waiting thread is now a) useless b) potential problem because when he will get result, it's completely useless and he will trigger callbacks that can lead to number of errors.

All of that and he can do response processing that could be CPU intense. And you, as a developer, cannot even stop it, because you can't throw if (Thread.currentThread().isInterrupted()) lines in all code.

So the inability to forcefully stop a thread it weird.

查看更多
初与友歌
4楼-- · 2018-12-31 01:37

There is no way to gracefully kill a thread.

You can try to interrupt the thread, one commons strategy is to use a poison pill to message the thread to stop itself

public class CancelSupport {
    public static class CommandExecutor implements Runnable {
            private BlockingQueue<String> queue;
            public static final String POISON_PILL  = “stopnow”;
            public CommandExecutor(BlockingQueue<String> queue) {
                    this.queue=queue;
            }
            @Override
            public void run() {
                    boolean stop=false;
                    while(!stop) {
                            try {
                                    String command=queue.take();
                                    if(POISON_PILL.equals(command)) {
                                            stop=true;
                                    } else {
                                            // do command
                                            System.out.println(command);
                                    }
                            } catch (InterruptedException e) {
                                    stop=true;
                            }
                    }
                    System.out.println(“Stopping execution”);
            }

    }

}

BlockingQueue<String> queue=new LinkedBlockingQueue<String>();
Thread t=new Thread(new CommandExecutor(queue));
queue.put(“hello”);
queue.put(“world”);
t.start();
Thread.sleep(1000);
queue.put(“stopnow”);

http://anandsekar.github.io/cancel-support-for-threads/

查看更多
不再属于我。
5楼-- · 2018-12-31 01:40

I want to add several observations, based on the comments that have accumulated.

  1. Thread.stop() will stop a thread if the security manager allows it.
  2. Thread.stop() is dangerous. Having said that, if you are working in a JEE environment and you have no control over the code being called, it may be necessary.
  3. You should never stop stop a container worker thread. If you want to run code that tends to hang, (carefully) start a new daemon thread and monitor it, killing if necessary.
  4. stop() creates a new ThreadDeath error on the calling thread and then causes that Error to be applied to the target thread. Therefore, the stack trace is generally worthless.
  5. In JRE 6, stop() checks with the security manager and then calls stop1() that calls stop0(). stop0() is native code.
查看更多
若你有天会懂
6楼-- · 2018-12-31 01:44

Generally you don't..

You ask it to interrupt whatever it is doing using Thread.interrupt() (javadoc link)

A good explanation of why is in the javadoc here (java technote link)

查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 01:45

See this thread by Sun on why they deprecated Thread.stop(). It goes into detail about why this was a bad method and what should be done to safely stop threads in general.

The way they recommend is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread terminate.

查看更多
登录 后发表回答