Java中注册进程退出时的清理函数_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java中注册进程退出时的清理函数

Java中注册进程退出时的清理函数

 2013/8/30 13:09:17  kabike  程序员俱乐部  我要评论(0)
  • 摘要:java里利用addShutdownHook可以添加一个线程,在jvm关闭时调用,执行一些清理工作publicstaticvoidmain(String[]args)throwsInterruptedException{ThreadshutdownHook=newThread(newRunnable(){@Overridepublicvoidrun(){System.out.println("jvmgoingdown!dosomethinghere!");}});Runtime
  • 标签:函数 Java
java里利用addShutdownHook可以添加一个线程,在jvm关闭时调用,执行一些清理工作

class="java" name="code">public static void main(String[] args) throws InterruptedException {
		Thread shutdownHook = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("jvm going down!do something here!");
			}

		});
		Runtime.getRuntime().addShutdownHook(shutdownHook);

		while (true) {
			TimeUnit.SECONDS.sleep(1);
		}

	}


但是这个线程不能保证总是工作.
引用In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.
所以kill -9的时候,就不能保证这个清理函数的执行了
发表评论
用户名: 匿名