How to properly stop the Thread in Java?

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

    You should always end threads by checking a flag in the run() loop (if any).

    Your thread should look like this:

    public class IndexProcessor implements Runnable {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
        private volatile boolean execute;
    
        @Override
        public void run() {
            this.execute = true;
            while (this.execute) {
                try {
                    LOGGER.debug("Sleeping...");
                    Thread.sleep((long) 15000);
    
                    LOGGER.debug("Processing");
                } catch (InterruptedException e) {
                    LOGGER.error("Exception", e);
                    this.execute = false;
                }
            }
        }
    
        public void stopExecuting() {
            this.execute = false;
        }
    }
    

    Then you can end the thread by calling thread.stopExecuting(). That way the thread is ended clean, but this takes up to 15 seconds (due to your sleep). You can still call thread.interrupt() if it's really urgent - but the prefered way should always be checking the flag.

    To avoid waiting for 15 seconds, you can split up the sleep like this:

            ...
            try {
                LOGGER.debug("Sleeping...");
                for (int i = 0; (i < 150) && this.execute; i++) {
                    Thread.sleep((long) 100);
                }
    
                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
            ...
    

提交回复
热议问题