简体   繁体   English

从stdin读取但无法知道何时停止

[英]Read from stdin but unable to know when to stop

I am running some commnads on commmand prompt. 我正在命令提示符下运行一些命令。 I am waiting for the last command's output to complete. 我正在等待最后一个命令的输出完成。 I have to read the output and perform the operation. 我必须阅读输出并执行操作。 My command's output is very dynamic and I can not predict when I can stop reading. 我的命令输出非常动态,无法预测何时停止读取。

I am having issues that I dont know when to stop reading. 我遇到了我不知道何时停止阅读的问题。 If suppose I keep the while read(), then my last command output is not ending with new line. 如果假设我保留while read(),那么我的最后一条命令输出不会以换行结尾。 Is there any mechenism which can tell me if there has been no activity on stdin for last 5mins, then I get some alert?? 是否有任何机制可以告诉我,如果最近5分钟stdin上没有任何活动,那么我会得到一些警惕吗?

The approach I took was to create a class implementing Runnable which monitors the value of a shared AtomicInteger flag. 我采用的方法是创建一个实现Runnable的类,该类监视共享的AtomicInteger标志的值。 This InputRunnable class sleeps for 5 minutes (300000 ms) and then wakes up to check whether the value has been set by the main method. InputRunnable类休眠5分​​钟(300000 ms),然后唤醒以检查是否已通过main方法设置该值。 If the user has entered at least one input in the last 5 minutes, then the flag would be set to 1, and InputRunnable will continue execution. 如果用户在最近5分钟内至少输入了一个输入,则该标志将设置为1, InputRunnable将继续执行。 If the user has not entered an input in the last 5 minutes, then the thread will call System.exit() which will terminate the entire application. 如果用户在最近5分钟内输入任何输入,则线程将调用System.exit() ,这将终止整个应用程序。

public class InputRunnable implements Runnable {
    private AtomicInteger count;

    public InputRunnable(AtomicInteger count) {
        this.count = count;
    }

    public void run() {
        do {
            try {
                Thread.sleep(300000);               // sleep for 5 minutes
            } catch (InterruptedException e) {
                // log error
            }

            if (count.decrementAndGet() < 0) {      // check if user input occurred
                System.exit(0);                     // if not kill application
            }
        } while(true);
    }
}

public class MainThreadClass {
    public static void main(String args[]) {
        AtomicInteger count = new AtomicInteger(0);
        InputRunnable inputRunnable = new InputRunnable(count);
        Thread t = new Thread(inputRunnable);
        t.start();

        while (true) {
            System.out.println("Enter a number:");
            Scanner in = new Scanner(System.in);
            int num = in.nextInt();                 // scan for user input

            count.set(1);
        }
    }
}

I tested this code locally and it appears to be working, but please let me know if you have any issues getting it to run on your system. 我在本地测试了此代码,它似乎可以正常工作,但是如果您在使它在系统上运行时遇到任何问题,请告诉我。

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

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