gpt4 book ai didi

java - 长时间运行的应用程序(类似尾部)

转载 作者:行者123 更新时间:2023-12-02 07:48:30 25 4
gpt4 key购买 nike

我想写一个类似尾部的应用程序。现在,这个应用程序会扫描文件以了解背景变化,并在发生变化时触发事件。

我想运行我的应用程序,直到用户请求按 ctrl + c 退出它(默认情况下工作)。我不想像做 ATM 那样仅仅通过执行无休止的 while(true) 循环来创建大量 CPU 负载:

try {
// thread doing the monitoring
thread.start();

// forcing the programm not to exit
while (System.in.available() == 0) {
Thread.sleep(5000);
}

} catch (final IOException e) {
e.printStackTrace();
}

有人知道更优雅/正确的方法吗?

最佳答案

我不知道为什么你首先要使用线程,“tail”unix 脚本只是一个没有退出条件的 while(true) 循环。它会监视文件并打印更改(如果检测到任何更改)。我认为默认情况下它会暂停 1 秒,所以基本上:

while(true) {
// Code goes here. Watch file, System.out.print if it changes

Thread.sleep(1000);
}

不需要线程。但要回答有关保持应用程序存活的最佳方法的问题:只需不要从线程的 run() 方法返回即可。您不必加入线程,只要应用程序有一个非守护程序运行线程,它就会停留在前台。

关于java - 长时间运行的应用程序(类似尾部),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10535388/

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