gpt4 book ai didi

java - 停止 Tomcat 应用程序中的线程 - 哪种方法?

转载 作者:行者123 更新时间:2023-11-28 21:56:42 24 4
gpt4 key购买 nike

我正在使用以下实现来停止 Tomcat 中的线程。代码有效,但我想知道两件事:

  1. MyConsumer.java的try语句中是否必须有Thread.sleep()?
  2. 不是检查我的 boolean 标志 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;
}
}

}

最佳答案

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)?

是的,那是我确实会做的。它将消除对标志的需要,并允许尽快停止线程,而不必在 1 秒后等待 sleep 调用返回。另一个优点是您可以在 doStuff() 方法中检查线程是否被中断,以防它是一个您想尽快停止的长时间运行的方法。

关于java - 停止 Tomcat 应用程序中的线程 - 哪种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14633772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com