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

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

             while(!shutdown)
            {                                  


        
3条回答
  •  星月不相逢
    2020-11-22 16:57

    Typically, a thread is terminated when it's interrupted. So, why not use the native boolean? Try isInterrupted():

       Thread t = new Thread(new Runnable(){
            @Override
            public void run() {
                while(!Thread.currentThread().isInterrupted()){
                    // do stuff         
                }   
            }});
        t.start();
    
        // Sleep a second, and then interrupt
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}
        t.interrupt();
    

提交回复
热议问题