package DestroyProcessTest;
/**
* @Author: ZhangHao
* @Description: 销毁进程测试
* @Date: 2020/6/6 11:12
* @Version: 1.0
*/
public class DestroyProcessTest {
public static void main(String[] args) throws InterruptedException {
new DestroyProcessTest().outOfMemoryTest();
}
private void activeExitTest() throws InterruptedException {
// 程序正常结束时会触发ShutdownHook
Thread runtimeShutDownThread = new Thread(() -> System.out.println("DestroyProcessTest"));
Runtime.getRuntime().addShutdownHook(runtimeShutDownThread);
Thread.sleep(3000);
}
private void outOfMemoryTest() throws InterruptedException {
// -Xmx=20m
// 堆内存超过设置的上限时,会触发ShutdownHook
// -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./out
// 内存溢出时生成的java_pid进程号.hprof默认在工程根目录,-XX:HeapDumpPath可以更改目录,hprof文件用jdk/bin/jvisualvm查看
Thread runtimeShutDownThread = new Thread(() -> System.out.println("DestroyProcessTest"));
Runtime.getRuntime().addShutdownHook(runtimeShutDownThread);
Object[] objectArray = new Object[Integer.MAX_VALUE];
for(int i = 0;i < objectArray.length;i++){
objectArray[i] = new Object();
}
Thread.sleep(Long.MAX_VALUE);
}
private void exitTest() throws InterruptedException {
// 手动关闭进程时不会触发ShutdownHook
Thread runtimeShutDownThread = new Thread(() -> System.out.println("DestroyProcessTest"));
Runtime.getRuntime().addShutdownHook(runtimeShutDownThread);
Thread.sleep(Long.MAX_VALUE);
}
}
package DestroyProcessTest;
/**
* @Author: ZhangHao
* @Description: 销毁进程测试
* @Date: 2020/6/6 11:28
* @Version: 1.0
*/
public class DestroyProcessTestThread extends Thread {
public DestroyProcessTestThread() {
this.setName("DestroyProcessTestThread");
}
public void start_server() {
Runtime.getRuntime().addShutdownHook(this);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
System.out.println("DestroyProcessTest");
}
public static void main(String[] args) {
DestroyProcessTestThread server = new DestroyProcessTestThread();
server.start_server();
}
}
package DestroyProcessTest;/**
* @Author: ZhangHao
* @Description: 销毁进程测试
* @Date: 2020/6/9 11:05
* @Version: 1.0
*/
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class DestroyProcessTestApplication extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// 关闭窗口会执行runtimeShutDownThread的run方法
Thread runtimeShutDownThread = new Thread(() -> System.out.println("DestroyProcessTest"));
Runtime.getRuntime().addShutdownHook(runtimeShutDownThread);
// 关闭窗口监听CloseRequest事件
primaryStage.setOnCloseRequest(event -> System.out.println("DestroyProcessTest1"));
Pane pane = new Pane();
primaryStage.setScene(new Scene(pane, 300, 300));
primaryStage.show();
}
}
java 遇到未知异常使程序崩溃,输出jvm的dump崩溃信息到指定文件,然后杀死此进程:https://blog.csdn.net/m0_37518406/article/details/78900393