跳过功能,如果时间过长(Skip function if it takes too long)

2019-08-31 15:40发布

在Java中我有处理以某种方式的文本文件的功能。 然而,如果花费太多的时间进程将最有可能是无用的(无论是什么原因是)为文本文件,我想跳过它。 此外,如果处理时间过长,它也使用了太多的内存。 我试图解决这种方式,但它不工作:

for (int i = 0; i<docs.size(); i++){
    try{
        docs.get(i).getAnaphora();
        }
    catch (Exception e){
        System.err.println(e);
    }
 }

其中, docs只是一个List目录中的文件的。 通常我都因为它是在一个特定的文件“卡住”(根据该文件的内容)手动停止代码。

有测量时间为函数调用,并告诉Java跳过函数有不止文件,比方说,10秒的方法吗?

编辑
刮了几个不同的答案在一起后,我想出了这个解决方案,它工作正常。 也许别人可以利用的想法也是如此。

首先创建一个实现可运行(这样你可以在参数如果需要传递给线程)类:

public class CustomRunnable implements Runnable {

    Object argument;

    public CustomRunnable (Object argument){
        this.argument = argument;
}

    @Override
    public void run() {
        argument.doFunction();
    }
}

然后使用这个代码在main类监控功能时( argument.doFunction()并退出,如果它需要长期:

Thread thread;
for (int i = 0; i<someObjectList.size(); i++){          
    thread = new Thread(new CustomRunnable(someObjectList.get(i)));
    thread.start();
    long endTimeMillis = System.currentTimeMillis() + 20000;
    while (thread.isAlive()) {
        if (System.currentTimeMillis() > endTimeMillis) {
        thread.stop();
        break;
    }
    try {
        System.out.println("\ttimer:"+(int)(endTimeMillis - System.currentTimeMillis())/1000+"s");
        thread.sleep(2000);
        }
    catch (InterruptedException t) {}
    }
}

我知道stop()被depcecated,但我还没有发现任何其他方式停止,当我希望它停止退出线程。

Answer 1:

包装你的代码中RunnableCallable ,并提交给合适的执行器来执行它。 一项所述的方法提交的需要,其之后已经过去被中断的代码在超时时段。



Answer 2:

你可以使用System.nanoTime()的run方法里面作为一个条件。

例如,

long cur = System.nanoTime(); //records the time when start executing
...
double elapsedTime(System.nanoTime() - cur) / 1000000.0; // at the end


文章来源: Skip function if it takes too long