Web服务停止并卸载后其启动的线程还在跑的可能原因
package org.example; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import java.time.LocalDateTime; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 使用注解模式配置Servlet的loadOnStartup时,需要同时设置了urlPatterns才能起作用,使用web.xml配置则不用 * * @Author: xurm 707669522@qq.com * @Date: 2023-09-22 * @Description: */ @WebServlet(loadOnStartup = 1, name = "timer", urlPatterns = "/") public class TimerServlet extends HttpServlet { /** * 创建一个定时任务调度线程池 */ private ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1); @Override public void init(ServletConfig config) throws ServletException { super.init(config); scheduledExecutorService.scheduleAtFixedRate(() -> { System.out.println(LocalDateTime.now()); }, 1000, 1000, TimeUnit.MILLISECONDS); System.out.println("\033[31m定时器初始化完成!\033[0m"); } @Override public void destroy() { super.destroy(); System.out.println("\033[35m卸载TimerServlet!\033[0m"); //必须手动关闭线程池,否则因为通过Sevlet启动的线程的生命周期是Web服务器级别的(或者说是JVM级别),只是当前Web停止时线程依旧在跑的 scheduledExecutorService.shutdown(); } }
以下是放如Tomcat里启动随后停止的效果:
23-Sep-2023 12:05:52.713 信息 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory 把web 应用 程序部署到目录 [D:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\webDemo] 定时器初始化完成! 23-Sep-2023 12:05:52.735 信息 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Web应用程序目录[D:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\webDemo]的部署已在[22]毫秒内完成 23-Sep-2023 12:05:52.746 信息 [main] org.apache.coyote.AbstractProtocol.start 开始协议处理句柄["http-nio-8080"] 23-Sep-2023 12:05:52.777 信息 [main] org.apache.catalina.startup.Catalina.start Server startup in 682 ms 2023-09-23T12:05:53.743001 2023-09-23T12:05:54.742991 2023-09-23T12:05:55.748843 2023-09-23T12:05:56.745415200 2023-09-23T12:05:57.755429 2023-09-23T12:05:58.746131200 2023-09-23T12:05:59.752523700 2023-09-23T12:06:00.748606100 2023-09-23T12:06:01.747062800 2023-09-23T12:06:02.750273900 卸载TimerServlet!