How to properly stop the Thread in Java?

后端 未结 9 1032
执念已碎
执念已碎 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

    Some supplementary info. Both flag and interrupt are suggested in the Java doc.

    https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

    private volatile Thread blinker;
    
    public void stop() {
        blinker = null;
    }
    
    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }
    

    For a thread that waits for long periods (e.g., for input), use Thread.interrupt

    public void stop() {
         Thread moribund = waiter;
          waiter = null;
          moribund.interrupt();
     }
    

提交回复
热议问题