如何在Java中正确停止线程?

2022-08-31 05:06:03

我需要一个解决方案来正确停止Java中的线程。

我有一个实现Runnable接口的类:IndexProcessor

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);

    @Override
    public void run() {
        boolean run = true;
        while (run) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                run = false;
            }
        }

    }
}

我有一个启动和停止线程的类:ServletContextListener

public class SearchEngineContextListener implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);

    private Thread thread = null;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        thread = new Thread(new IndexProcessor());
        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) {
            thread.interrupt();
            LOGGER.debug("Thread successfully stopped.");
        }
    }
}

但是当我关闭 tomcat 时,我的 IndexProcessor 类中出现了异常:

2012-06-09 17:04:50,671 [Thread-3] ERROR  IndexProcessor Exception
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at lt.ccl.searchengine.processor.IndexProcessor.run(IndexProcessor.java:22)
    at java.lang.Thread.run(Unknown Source)

我使用的是 JDK 1.6。所以问题是:

如何停止线程而不引发任何异常?

附言我不想使用方法,因为它已被弃用。.stop();


答案 1

使用是一种完全可以接受的方式。实际上,它可能比上面建议的标志更可取。原因是,如果您处于可中断的阻塞调用中(例如或使用java.nio通道操作),您实际上将能够立即突破这些操作。Thread.interrupt()Thread.sleep

如果使用标志,则必须等待阻止操作完成,然后才能检查标志。在某些情况下,无论如何你都必须这样做,例如使用标准/这是不可中断的。InputStreamOutputStream

在这种情况下,当线程中断时,它不会中断IO,但是,您可以在代码中轻松例行执行此操作(并且您应该在可以安全地停止和清理的战略点执行此操作)

if (Thread.currentThread().isInterrupted()) {
  // cleanup and stop execution
  // for example a break in a loop
}

就像我说的,主要优点是你可以立即中断调用,这是标志方法无法做到的。Thread.interrupt()


答案 2

在类中,您需要一种设置标志的方法,该标志通知线程它需要终止,类似于您在类作用域中使用的变量。IndexProcessorrun

当您希望停止线程时,请设置此标志并调用线程并等待它完成。join()

通过使用易失性变量或使用 getter 和 setter 方法(与用作标志的变量同步),确保该标志是线程安全的。

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;
            }
        }

    }
}

然后在: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.");
        }
    }
}