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

Tim*_*Tim 8 java multithreading timer function-call

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

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

where 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在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) {}
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*sen 8

将代码包装在Runnable或中Callable,并将其提交给合适的执行程序以执行它.其中一个提交方法需要一段超时时间,之后代码被中断.