gpt4 book ai didi

钩子线程实战

转载 作者:知者 更新时间:2024-03-13 03:16:27 27 4
gpt4 key购买 nike

一 点睛

JVM 进程的退出是由于 JVM 进程中没有活跃的非守护线程,或者收到了系统中断信号,向 JVM 程序注入一个 Hook 线程,在 JVM 进程退出的时候,Hook 线程会启动执行,通过 RunTime 可以为 JVM 注入多个 Hook 线程。

二 实战

1 代码

package concurrent;

import java.util.concurrent.TimeUnit;

public class ThreadHook {
    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("The hook thread 1 is running.");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("The hook thread 1 will exit");
        }));

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("The hook thread 2 is running.");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("The hook thread 2 will exit");
        }));

        System.out.println("The program will is stopping");
    }
}

2 测试

The program will is stopping

The hook thread 2 is running.

The hook thread 1 is running.

The hook thread 2 will exit

The hook thread 1 will exit

3 说明

给 Java 程序注入了两个 Hook 线程,在 main 线程中结束,也就是 JVM 中没有了活动的非守护线程,JVM 进程即将退出时,两个 Hook 线程会被启动并且运行。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com