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...");
});
}
}
}
}
Java优雅停止应用程序
最新推荐文章于 2024-04-17 16:48:11 发布