【发布时间】:2013-01-31 19:37:35
【问题描述】:
我正在使用以下实现来停止 Tomcat 中的线程。该代码有效,但我想知道两件事:
- MyConsumer.java的try语句中是否必须要有Thread.sleep()?
- 不检查我的布尔标志
running,我是否应该删除标志的概念而只检查while(!Thread.currentThread().isInterrupted)?
ServletContextListener:
public final class ApplicationListener implements ServletContextListener {
private Thread thread = null;
private MyConsumer k = null;
public ApplicationListener() {
}
@Override
public void contextInitialized(ServletContextEvent event) {
k = new MyConsumer();
thread = new Thread(k);
thread.start();
}
@Override
public void contextDestroyed(ServletContextEvent event) {
if (thread != null) {
k.terminate();
try {
thread.join();
} catch (InterruptedException ex) {
Logger.getLogger(ApplicationListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
MyConsumer.java:
public class MyConsumer implements Runnable {
private volatile boolean running = true;
public MyConsumer() {
}
public void terminate() {
running = false;
}
@Override
public void run() {
while (running) {
try {
doStuff();
Thread.sleep((long) 1000);
} catch (InterruptedException ex) {
Logger.getLogger(MyConsumer.class.getName()).log(Level.SEVERE, null, ex);
running = false;
}
}
}
【问题讨论】:
标签: java multithreading apache tomcat