How do you kill a Thread in Java?

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

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

16条回答
  •  再見小時候
    2020-11-21 06:50

    'Killing a thread' is not the right phrase to use. Here is one way we can implement graceful completion/exit of the thread on will:

    Runnable which I used:

    class TaskThread implements Runnable {
    
        boolean shouldStop;
    
        public TaskThread(boolean shouldStop) {
            this.shouldStop = shouldStop;
        }
    
        @Override
        public void run() {
    
            System.out.println("Thread has started");
    
            while (!shouldStop) {
                // do something
            }
    
            System.out.println("Thread has ended");
    
        }
    
        public void stop() {
            shouldStop = true;
        }
    
    }
    

    The triggering class:

    public class ThreadStop {
    
        public static void main(String[] args) {
    
            System.out.println("Start");
    
            // Start the thread
            TaskThread task = new TaskThread(false);
            Thread t = new Thread(task);
            t.start();
    
            // Stop the thread
            task.stop();
    
            System.out.println("End");
    
        }
    
    }
    

提交回复
热议问题