在JVM关闭的时候线程该怎么关闭呢

     在编写线程类的时候设置一个标志,用于表示是否开始执行线程内容的业务。当JVM关闭的线程也关闭,那么就需要在在JVM中注册线程,在关闭的时候关闭线程。

package easyway.tbs.transfer.config;

import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.log4j.Logger;
/**
 * FTP客户端服务启动的服务
 * @author  longgangbai
 *
 */
public class FtpClientServiceDaemon  {
	private static final Logger logger = Logger.getLogger(FtpClientServiceDaemon.class);
	/**
	 * 开始启动的进程
	 * @param args
	 */
	public static void main(String[] args) {
		AtomicBoolean  running=new AtomicBoolean(true);
		FtpServiceDaemonThread app = new FtpServiceDaemonThread(running);
	    Runtime.getRuntime().addShutdownHook(new ShutdownHook(app));
	    Thread thread=new Thread(app);
	    logger.info("FtpClientServiceDaemon 开始启动......");
	    thread.start();
	}
	/**
	 * JVM关闭时候执行的线程方法
	 * @author longgangbai
	 *
	 */
	public static class ShutdownHook extends Thread
	{
	        private final FtpServiceDaemonThread instance;

	        public ShutdownHook(FtpServiceDaemonThread instance)
	        {
	            this.instance = instance;
	        }
	        public void run()
	        {
	        	logger.info("Shutting down");
	            try {
	                instance.stop();
	            }
	            catch (Exception e) {
	            	logger.error(e.getMessage());
	                e.printStackTrace(System.err);
	            }
	        }
	}

}

 

你可能感兴趣的:(jvm)