问题描述
在Java中,我有一个以某种方式处理文本文件的函数。但是,如果花费太多时间,该过程很可能对该文本文件无用(无论什么原因),我想跳过它。此外,如果过程耗时太长,它也会占用太多内存。我试图用这种方式解决它,但它不起作用:
In Java I have a function that processes a text file in a certain way. However, if it takes too much time the process will most likely be useless (whatever the reason is) for that text file and I would like to skip it. Furthermore, if the process takes too long, it also uses too much memory. I've tried to solve it this way, but it doesn't work:
for (int i = 0; i<docs.size(); i++){
try{
docs.get(i).getAnaphora();
}
catch (Exception e){
System.err.println(e);
}
}
其中 docs
只是目录中文件的列表
。通常我必须手动停止代码,因为它卡在特定文件(取决于该文件的内容)。
where docs
is just a List
of files in a directory. Usually I have to manually stop the code because it is 'stuck' at a particular file (depending on the contents of that file).
有没有办法测量该函数调用的时间,并告诉Java跳过该函数所需的文件,比如10秒?
Is there a way of measuring time for that function call and tell Java to skip the file the function takes more than, let's say, 10 seconds?
编辑
在拼凑出几个不同的答案之后,我想出了这个解决方案,效果很好。也许其他人也可以使用这个想法。
EDIT
After scraping a few different answers together I came up with this solution which works fine. Perhaps someone else can use the idea as well.
首先创建一个实现Runable的类(这样你可以根据需要将参数传递给Thread):
First create a class that implements Runable (this way you can pass in arguments to the Thread if needed):
public class CustomRunnable implements Runnable {
Object argument;
public CustomRunnable (Object argument){
this.argument = argument;
}
@Override
public void run() {
argument.doFunction();
}
}
然后在 main 类来监视函数的时间( argument.doFunction()
)并退出,如果它需要很长时间:
Then use this code in the main
class to monitor the time of a function (argument.doFunction()
) and exit if it takes to long:
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()
已经被删除了,但是当我希望它停止时,我还没有找到任何其他方法来停止和退出该线程。
I realise stop()
is depcecated, but I haven't found any other way to stop and exit the thread when I want it to stop.
推荐答案
将代码包装在 Runnable
或 Callable中
并将其提交给合适的Executor来执行它。其中一个提交方法需要一段超时时间,之后代码被中断。
Wrap your code in a Runnable
or Callable
and submit it to a suitable Executor to execute it. One of the submit method takes a timeout period after which has passed the code is interrupted.
这篇关于跳过功能,如果它需要太长时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!