如果进程在java中花费的时间超过指定的时间,则会中断while循环

时间:2015-03-09 16:17:34

标签: java while-loop

在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”也不起作用。

4 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

简单地说:

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

答案 2 :(得分:0)

当你的while循环阻塞在&#34; x = fromServer.readline();&#34;您可以将读者实例共享到另一个线程,并在超时后使该线程关闭读取器。这将导致readLine抛出您可以处理并继续的异常。

答案 3 :(得分:0)

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

尝试以下方法:

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