gpt4 book ai didi

java - (Java) 退出循环 "remotely"

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:38:10 27 4
gpt4 key购买 nike

我有一段 Java 程序主要执行以下操作:

public static void main(String[] args)
{
while(true)
{
// does stuff ...
}
}

无限循环是有意设计的——当任其发展时,程序将无限循环。在大多数情况下,它工作正常。但是,有时我想把程序拿下来维护,当我把它拿下来时,我想确保它运行完循环中的所有代码,直到结束然后退出。

我想知道最好的解决方案是什么。我想到的一个想法是做这样的事情:

public static void main(String[] args)
{
File f = new File("C:\exit.txt");
while(!f.exists())
{
// does stuff ...
}
}

这基本上允许我通过创建一个名为“exit.txt”的文件优雅地退出循环。这对我的目的来说可能没问题,但我想知道是否有更好的替代方法。

最佳答案

我认为 Java 7 中引入的 WatchService 可能在这里有用(如果您更喜欢基于文件的方法)。来自JavaDocs :

A watch service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.

基本上这意味着您可以设置一个 WatchService 来监视文件夹的更改。发生更改时,您可以选择要采取的操作。

以下代码使用 WatchService 来监视指定文件夹的更改。当发生更改时,它会执行调用者提供的 Runnable(方法 runWhenItIsTimeToExit)。

public class ExitChecker {
private final Path dir;
private final Executor executor;
private final WatchService watcher;

// Create the checker using the provided path but with some defaults for
// executor and watch service
public ExitChecker(final Path dir) throws IOException {
this(dir, FileSystems.getDefault().newWatchService(), Executors.newFixedThreadPool(1));
}

// Create the checker using the provided path, watcher and executor
public ExitChecker(final Path dir, final WatchService watcher, final Executor executor) {
this.dir = dir;
this.watcher = watcher;
this.executor = executor;
}

// Wait for the folder to be modified, then invoke the provided runnable
public void runWhenItIsTimeToExit(final Runnable action) throws IOException {
// Listen on events in the provided folder
dir.register(watcher,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);

// Run it async, otherwise the caller thread will be blocked
CompletableFuture.runAsync(() -> {
try {
watcher.take();
} catch (InterruptedException e) {
// Ok, we got interrupted
}
}, executor).thenRunAsync(action);
}
}

那么,我们如何使用检查器呢?那么,下面的代码说明了这一点:

public static void main(String... args) throws IOException, InterruptedException {
// Setup dirs in the home folder
final Path directory = Files.createDirectories(
new File(System.getProperty("user.home") + "/.exittst").toPath());

// In this case we use an AtomicBoolean to hold the "exit-status"
AtomicBoolean shouldExit = new AtomicBoolean(false);

// Start the exit checker, provide a Runnable that will be executed
// when it is time to exit the program
new ExitChecker(directory).runWhenItIsTimeToExit(() -> {
// This is where your exit code will end up. In this case we
// simply change the value of the AtomicBoolean
shouldExit.set(true);
});

// Start processing
while (!shouldExit.get()) {
System.out.println("Do something in loop");
Thread.sleep(1000);
}

System.out.println("Exiting");
}

最后,如何退出程序呢?只需触摸指定文件夹中的文件即可。示例:

cd ~/.exittst
touch exit-now.please

资源:

关于java - (Java) 退出循环 "remotely",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27734969/

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