How to properly stop the Thread in Java?

后端 未结 9 1035
执念已碎
执念已碎 2020-11-21 16:19

I need a solution to properly stop the thread in Java.

I have IndexProcessorclass which implements the Runnable interface:

public class          


        
9条回答
  •  情书的邮戳
    2020-11-21 16:48

    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();
    

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

提交回复
热议问题