package org.example.shutdown;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main1 {
public static ExecutorService executorService = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("hook 1");
executorService.submit(() -> {
System.out.println("run in hook");
});
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hook 2");
System.out.println("shut down end");
}));
executorService.submit(() -> {
System.out.println("run");
});
System.out.println("ok");
System.out.println("shut down before1");
// 体会下这行代码的作用
System.exit(1);
System.out.println("shut down before2"); // 这段代码执行不到了
}
}
/*
ok
shut down before1
run
hook 1
run in hook
hook 2
shut down end
*/
总结:有了 这个exit1,我们尽管在hook中写清理 逻辑 就行。