gpt4 book ai didi

java - 如果花费的时间太长则跳过函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:50 25 4
gpt4 key购买 nike

在 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 秒的文件?

编辑
在拼凑了几个不同的答案后,我想出了这个效果很好的解决方案。也许其他人也可以使用这个想法。

首先创建一个实现 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()),如果时间过长则退出:

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() 已被删除,但我还没有找到任何其他方法来停止并在我希望它停止时退出线程。

最佳答案

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

关于java - 如果花费的时间太长则跳过函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16121176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com