【问题标题】:Breaking out of a while loop if the process takes more than a specified amount of time in java如果进程在 java 中花费的时间超过指定的时间量,则退出 while 循环
【发布时间】:2015-03-09 16:17:34
【问题描述】:

在 UI 上执行事件后,我正在读取服务器日志文件。我有一个while循环,它等待某些条件匹配,然后返回日志的那一行。但是,有时在代码查看日志之前发生事件并且无法获取新行的情况。这会导致 while 循环挂起,并一直挂起,直到在提供的条件下发生另一个事件。由于显而易见的原因,这是有问题的。不管是什么情况,有没有办法在几秒钟后跳出 while 循环?以下是我的代码

   public String method(String, a, String b, String c) { 
    channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(a + "\n" +  b);
        channel.connect();
        fromServer = new BufferedReader (new InputStreamReader(channel.getInputStream()));          
        String time = methodToFireAnEventInUI();
        Thread.sleep(2000);
        String x = null;
        while (true){
            x = fromServer.readLine();
            if(!x.equals(null) && x.contains(c) && x.contains(time)){
                break;
            }
        }
        msg = x.toString();
    }catch (Exception e){
        e.printStackTrace();
    }
    closeConnection();
    return msg;
    }

如果你看上面的代码,它就挂在“x = fromServer.readline();”处只是不会去任何地方,这就是我希望它的逻辑等待 x 时间并在那之后中止循环的地方。 我在 while 循环之前尝试“thread.sleep”也不起作用。

【问题讨论】:

  • readline 是一个阻塞调用。您无法在同一个线程中执行任何操作来解决呼叫挂起问题。

标签: java while-loop


【解决方案1】:

你可以把这个逻辑放在一个单独的线程中,像这样使用一段时间:

class TestThread extends Thread {

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            method();
        }       

    }

    public void method() {
        try {
            // this method hangs. You can replace it with your method
            while (true) {
                sleep(100);
            }
        } catch (Exception e) {
            System.out.println("Thread is interrupted");
        }
    }
}

之后,如果它需要更长的时间,你可以中断这个线程:

public static void main(String[] args) throws Exception {
    TestThread t1 = new TestThread();
    long startTime = System.currentTimeMillis();
    t1.start();
    long currentTime = System.currentTimeMillis();
    while (currentTime - startTime < 5000) { // you can decide the desired interval
        sleep(1000); // sleep some time
        currentTime = System.currentTimeMillis();
        System.out.println(currentTime); //print this to ensure that the program is still running
    }
    t1.interrupt(); //interrupt the thread
}

【讨论】:

  • 这看起来很有希望,你能详细说明一下吗?那么我应该在while循环中调用我的“方法”吗?之后如何使用“t1.start() 和中断”方法?我以前从未使用过这种技术..
【解决方案2】:

简单地说:

long timeOut = System.currentTimeMillis() + 5000; // change the value to what ever(millis)
while(System.currentTimeMillis() < timeOut){
    // do whatever 
}

【讨论】:

  • 我实际上已经尝试过了,但问题是,一旦它进入循环,它就不会出来检查这里提供的条件。因此,不幸的是,它只是不起作用。
  • 我倾向于相信除了@Thabang Masigo 解决方案之外还有其他方法可以实现这一目标,我只是不确定将InputStream 传递给Thread 是最好的解决方案。
  • @Donshon This 可能会有所帮助。
【解决方案3】:

作为“x = fromServer.readline();”处的 while 循环块您可以将阅读器实例共享给另一个线程,并让该线程在超时后关闭阅读器。这将导致您的 readLine 抛出您可以处理并继续的异常。

【讨论】:

    【解决方案4】:

    在这里寻找答案: How do I measure time elapsed in Java?

    试试下面的方法:

    long startTime = System.nanoTime(); //fetch starting time
    while(true ||(System.nanoTime()-startTime)<200000)
    {
        // do something
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 2022-01-14
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 2023-01-30
      相关资源
      最近更新 更多