跳过function,如果它需要太长时间

在Java中,我有一个以某种方式处理文本文件的函数。 但是,如果花费太多时间,该过程很可能对该文本文件无用(无论什么原因),我想跳过它。 此外,如果过程耗时太长,它也会占用太多内存。 我试图用这种方式解决它,但它不起作用:

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

其中docs只是List的文件List 。 通常我必须手动停止代码,因为它“卡在”特定文件(取决于该文件的内容)。

有没有办法测量该函数调用的时间并告诉Java跳过该函数所需的文件,比如10秒?

编辑
在将几个不同的答案拼凑在一起后,我想出了这个解决方案,它运行正常。 也许其他人也可以使用这个想法。

首先创建一个实现Runable的类(这样你可以根据需要将参数传递给Thread):

 public class CustomRunnable implements Runnable { Object argument; public CustomRunnable (Object argument){ this.argument = argument; } @Override public void run() { argument.doFunction(); } } 

然后在main类中使用此代码来监视函数的时间( argument.doFunction() ),如果需要long则退出:

 Thread thread; for (int i = 0; i endTimeMillis) { thread.stop(); break; } try { System.out.println("\ttimer:"+(int)(endTimeMillis - System.currentTimeMillis())/1000+"s"); thread.sleep(2000); } catch (InterruptedException t) {} } } 

我意识到stop()已经被删除了,但是当我希望它停止时,我还没有找到任何其他方法来停止和退出该线程。

将代码包装在RunnableCallable ,并将其提交给合适的Executor来执行它。 其中一个提交方法需要超时时间,之后代码被中断。

您可以在run方法中使用System.nanoTime()作为条件。

例如,

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