Ich brauche eine Lösung, um den Thread in Java richtig zu stoppen.
Ich habe eine IndexProcessor
Klasse, die die Runnable-Schnittstelle implementiert:
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;
}
}
}
}
Und ich habe eine ServletContextListener
Klasse, die den Thread startet und stoppt:
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.");
}
}
}
Wenn ich Tomcat herunterfahre, wird in meiner IndexProcessor-Klasse die Ausnahme angezeigt:
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)
Ich benutze JDK 1.6. Die Frage ist also:
Wie kann ich den Thread stoppen und keine Ausnahmen auslösen?
PS Ich möchte keine .stop();
Methode verwenden, da diese veraltet ist.
InterruptedException
finden Sie unter ibm.com/developerworks/library/j-jtp05236 .
InterruptedException
. Das denke ich, aber ich frage mich auch, wie der Standardweg ist.