How to properly stop the Thread in Java?

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

    In the IndexProcessor class you need a way of setting a flag which informs the thread that it will need to terminate, similar to the variable run that you have used just in the class scope.

    When you wish to stop the thread, you set this flag and call join() on the thread and wait for it to finish.

    Make sure that the flag is thread safe by using a volatile variable or by using getter and setter methods which are synchronised with the variable being used as the flag.

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

    Then in SearchEngineContextListener:

    public class SearchEngineContextListener implements ServletContextListener {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);
    
        private Thread thread = null;
        private IndexProcessor runnable = null;
    
        @Override
        public void contextInitialized(ServletContextEvent event) {
            runnable = new IndexProcessor();
            thread = new Thread(runnable);
            LOGGER.debug("Starting thread: " + thread);
            thread.start();
            LOGGER.debug("Background process successfully started.");
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent event) {
            LOGGER.debug("Stopping thread: " + thread);
            if (thread != null) {
                runnable.terminate();
                thread.join();
                LOGGER.debug("Thread successfully stopped.");
            }
        }
    }
    

提交回复
热议问题