在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,但我还没有发现任何其他方式停止,当我希望它停止退出线程。