当条件堆叠时,如何在Java中打破“while”循环

时间:2013-12-16 14:42:28

标签: java

我有以下Java代码:

while( someMethod() )   {

   //do something
}

someMethod()使用正则表达式解析一些文本。当文件太大时,可能需要花费太多时间,我宁愿打破它。 如果someMethod()耗尽时间,我怎么能设置超时并打破循环?

谢谢!

P.S。重要:someMethod()不是我的代码,我无法改变它

3 个答案:

答案 0 :(得分:1)

完整的应用程序包括导入:

package javaapplication4;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

public class JavaApplication4 {

    private static final ExecutorService pool = Executors.newSingleThreadExecutor();

    private static boolean someMethod(long i) throws InterruptedException {
        Thread.sleep(i*1000);
        return true;
    }

    private static boolean someMethodTimeOut(long timeOut, final long i) throws InterruptedException, ExecutionException, TimeoutException {
        Future<Boolean> res = pool.submit(new Callable<Boolean> (){
            @Override
            public Boolean call() throws Exception {
                return someMethod(i);
            }
        });

        return res.get(timeOut, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) {
        final long timeout = 5000;
        long i = 0;

        try {
            while(someMethodTimeOut(timeout, i++)) {
                System.out.println(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            pool.shutdownNow();
        }

    }

}

答案 1 :(得分:0)

实现someMethod,使其在达到指定限制时返回false:

boolean someMethod() {
    long endTimeMillis = System.currentTimeMillis() + 10000;
    while (true) {
        // your code logic, you should also set yourChosenTimeoutInMillis here.

        if (System.currentTimeMillis() > yourChosenTimeoutInMillis) {
            return false;
        }
    }
}

这样,如果someMethod在其核心逻辑中陷入无限循环,你的while将会退出。

答案 2 :(得分:0)

一种方法是创建一个调用该方法的新线程,然后在主线程中调用Thread.join(long timeout)。

 public class ParserThread extends Thread
    {

    private volatile success = false

    @Override
    public void run()
    { 
        success = someMethod();
    }

    @Override
    public void interrupt()
    {
        // TODO: try to cancel your logic here if possible to avoid wasted CPU cycles.
    }

    public boolean isSuccess()
    {
        return this.success;
    }
}

在你的主要课程中:

ParserThread t = new ParserThread();
t.start();

t.join(5000); // Wait a maximum for 5 second for example

if(t.isSuccess())
{
    // Do something if success
}
else
{
    // Do something else if failure
}