简体   繁体   English

在运行时将命令发送到命令行Java程序

[英]Send commands to a command line Java program while it is working

I have a Java program processing a large set of XML files. 我有一个处理大量XML文件的Java程序。 The process takes several hours to run and sometimes I need to stop. 该过程需要几个小时才能运行,有时我需要停止。 For now I use CTRL-C to kill it, make a note of which file it was working on, and later I remove the data for those files and re-process them. 现在,我使用CTRL-C杀死它,记下该文件正在处理的文件,然后删除这些文件的数据并重新处理它们。

Is there a way to have Java keep working while waiting for user input on the command line, and furthermore can I have it keep outputting log info to the command prompt while it listens? 有没有一种方法可以让Java在等待用户在命令行上输入时继续工作,而且我可以让它在监听时继续将日志信息输出到命令提示符吗?

I considered having it wait for user input a few seconds between files, but this would add more time to overall processing, and I'm not sure there's a way to timeout user input easily. 我考虑过让它在文件之间等待用户输入几秒钟,但这会增加整体处理时间,而且我不确定是否有一种方法可以轻松使用户输入超时。

You're interested in spawning another thread for your XML processor to run in. Look to the java.util.concurrent library. 您有兴趣为XML处理器生成另一个线程来运行。查看java.util.concurrent库。

Your main thread can handle user input while the other thread can report to the console. 您的主线程可以处理用户输入,而另一个线程可以向控制台报告。 Handling any concurrency issues between the two can be difficult, it's best advised to avoid communicating between the two as much as possible to save yourself headaches. 处理两者之间的任何并发问题可能很困难,最好避免在两者之间进行尽可能多的交流,以免造成麻烦。

You'll end up adding code that looks something like 您最终将添加类似于以下内容的代码

Thread xmlProcessorThread = new Thread(yourRunnableXMLProcessor);
xmlProcessorThread.run();

And adding the runnable interface to your XML processor (hence the name yourRunnableXMLProcessor ) 并将runnable接口添加到您的XML处理器(因此名称为yourRunnableXMLProcessor

In your command line application start a new thread that actually does the work of processing files. 在命令行应用程序中,启动一个实际上执行文件处理工作的新线程。 The processing thread could check an internal flag after each file and determine whether to continue or not. 处理线程可以在每个文件之后检查内部标志,并确定是否继续。 The main application thread would continue to listen for command line input and could set the value of the flag based on when it receives input. 主应用程序线程将继续侦听命令行输入,并可以根据接收到输入的时间设置标志的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM