How do you kill a Thread in Java?

前端 未结 16 2358
天命终不由人
天命终不由人 2020-11-21 05:54

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

16条回答
  •  被撕碎了的回忆
    2020-11-21 06:41

    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 queue;
                public static final String POISON_PILL  = “stopnow”;
                public CommandExecutor(BlockingQueue 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 queue=new LinkedBlockingQueue();
    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/

提交回复
热议问题