有人可以帮我解决这个问题吗?下面的代码是我用来启动/停止某些轮询服务的代码。轮询服务使用 while(boolean running)
循环运行。调用 Polling.setRunning(false)
将终止循环。
private static ExecutorService pool = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setDaemon(true);
return thread;
}
});
public static void start(){
pool.submit(new Runnable() {
public void run(){
try{
System.out.println("Starting Polling...");
Polling.start();
} catch(Exception e){
e.printStackTrace();
}
}
});
}
public static void stop(){
System.out.println("Stopping Polling...");
Polling.setRunning(false);
pool.shutDownNow();
}
public static void main(String[] args) throws Exception {
start(); //call to start
Thread.sleep(5000);
stop(); //call to stop
}
问题是:当我运行它时,一切正常并且符合预期。但是,当我运行时:
ps -ef | grep java
显示程序仍在后台运行。即使轮询服务肯定已停止!
为什么会这样?我能做些什么来修复它?
最佳答案
您需要进行线程转储以查看哪些非守护线程仍在运行。
jstack
、visualvm
或 jconsole
是执行此操作的几种方法。
您可以强制应用程序停止
System.exit(0);
由于轮询是在守护线程中进行的,因此它是否停止并不重要。不管怎样,程序都会完成。
关于关闭后Java线程仍在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7333716/