我正在使用下面的实现来停止 Tomcat 中的线程。该代码有效,但我想知道两件事:
- MyConsumer.java的try语句中是否需要有Thread.sleep()?
- 我是否应该删除标志的概念并只检查
while(!Thread.currentThread().isInterrupted)
,而不是检查 boolean 标志running
?
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;
}
}
}
最佳答案
Is it necessary to have Thread.sleep() in the try statement of MyConsumer.java
没有。我认为 sleep 调用是为了确保 doStuff()
每次调用之间间隔 1 秒执行,而不是连续执行。如果您想要 1 秒的间隔,则需要将 sleep 调用留在那里。如果你想要doStuff()
要连续执行,则需要去掉sleep。
Instead of checking for my boolean flag, running, should I remove the concept of a flag and just check for while(!Thread.currentThread().isInterrupted)?
是的,我确实会这么做。它将消除对标志的需要,并允许尽快停止线程,而不必等待 sleep 调用在 1 秒后返回。另一个优点是你可以检查doStuff()
内线程是否被中断。方法,以防您想尽快停止它是一个长时间运行的方法。
关于java - 停止 Tomcat 应用程序中的线程 - 哪种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14633772/