java 如何优雅的阻塞主线程

在某些时候,尤其是不带有容器的spring boot框架,需要阻塞主线程,防止程序退出,方便一些定时任务的执行。

一般可以直接使用下面的方法,阻塞主线程,可是这种方法不够的优雅。

@ImportResource("classpath:spring.xml")
@SpringBootApplication
public class App {
    
    

    private static final Logger LOG = LoggerFactory.getLogger(App.class);
    public static ApplicationContext context;

    public static void main(String[] args) {
    
    
        LOG.info("[init applications]");
        context = SpringApplication.run(App.class, args);
        LOG.info("[start run]");
        // 卡死主线程
        synchronized (App.class) {
    
    
            while (true) {
    
    
                try {
    
    
                    App.class.wait();
                } catch (Throwable e) {
    
    
                    LOG.error("error", e);
                }
            }
        }
    }
}

有一种足够优雅的方式:

@ImportResource("classpath:spring.xml")
@SpringBootApplication
public class App {
    
    

    private static final Logger LOG = LoggerFactory.getLogger(App.class);
    public static ApplicationContext context;

    public static void main(String[] args) throws InterruptedException {
    
    
        // 计数器 用于阻塞主线程
        CountDownLatch countDown = new CountDownLatch(1);
        // 注册钩子函数 当程序收到"kill"信号时 执行countDown
        Runtime.getRuntime().addShutdownHook(new Thread(countDown::countDown));
        LOG.info("[init applications]");
        context = SpringApplication.run(App.class, args);
        LOG.info("[start run]");
        // 阻塞主线程 等待"kill"信号 不要执行"kill -9"这会导致程序直接强制退出 无法正常关闭
        countDown.await();
        // 正常结束主线程 结束程序
        LOG.info("[stop run]");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44927769/article/details/131071052