我需要一個解決方案來正確地停止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
我沒有經常使用線程,所以我對線程非常陌生,所以我不知道忽略異常是否是正常行爲。這就是我問的原因。 –