Java優雅停止應用程序


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 優雅停止應用測試
 */
public class ShutdownHookTest {
    /**
     * 是否停止應用標識
     */
    public final static AtomicBoolean IS_SHUTDOWN = new AtomicBoolean(false);

    //創建關閉應用的鉤子函數
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            IS_SHUTDOWN.set(true);
            System.out.println("APP is going to shutdown after 5 seconds...");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("shutdown!");
        }));
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        while (true) {
            //如果終止APP標識爲true,終止線程池,停止處理任務
            if (IS_SHUTDOWN.get()) {
                executor.shutdown();
                break;
            } else {
                //執行任務
                Thread.sleep(1000);
                executor.submit(() -> {
                    System.out.println("I'm working...");
                });
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章