How can I kill a thread? without using stop();

后端 未结 3 560
Happy的楠姐
Happy的楠姐 2020-11-22 16:56
Thread currentThread=Thread.currentThread();
        public void run()
        {               

             while(!shutdown)
            {                                  


        
3条回答
  •  -上瘾入骨i
    2020-11-22 17:22

    Good way to do it would be to use a boolean flag to signal the thread.

    class MyRunnable implements Runnable {
    
        public volatile boolean stopThread = false;
    
        public void run() {
                while(!stopThread) {
                        // Thread code here
                }
        }
    
    }
    

    Create a MyRunnable instance called myrunnable, wrap it in a new Thread instance and start the instance. When you want to flag the thread to stop, set myrunnable.stopThread = true. This way, it doesn't get stopped in the middle of something, only where we expect it to get stopped.

提交回复
热议问题