我需要一个解决方案来正确地停止Java中的线程。如何在Java中正确地停止线程?
我有IndexProcessor
类实现Runnable接口:
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。所以问题是:
如何停止线程并不抛出任何异常?
P.S.我不想使用.stop();
方法,因为它已被弃用。
终止线程半路上总是会产生异常。如果这是正常行为,那么你可以捕获并忽略'InterruptedException'。这是我的想法,但我也想知道标准的方式。 – nhahtdh
如何使用'join()'? – Havelock
我没有经常使用线程,所以我对线程非常陌生,所以我不知道忽略异常是否是正常行为。这就是我问的原因。 –