Runtime.getRuntime().addShutdownHook

public class Main {

    /**
     * running 的值变化时,其他线程会得到感知
     */
    private static volatile boolean running = true;

    public static void main(String[] args) {

        // 正常停止应用时调用此方法,此方法使用一个线程
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {

                /**
                 * TODO 处理业务代码,例如 Spring 微服务的容器在销毁前,执行一些逻辑
                 */
                synchronized (Main.class) {
                    running = false;
                    // 唤醒等待的线程
                    Main.class.notify();
                }

            }
        }, "threadName"));

        synchronized (Main.class) {
            // 监听 running 是否变化
            while (running) {
                try {
                    // 使当前线程进入 WAITING 状态,并释放锁
                    Main.class.wait();
                } catch (Throwable e) {
                }
            }
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_30038111/article/details/81251828
今日推荐