Java 如何设置块的超时?

Java 如何设置块的超时?,java,timer,profiling,Java,Timer,Profiling,如果语句块在特定的时间间隔内没有完成,我想跳过它 比如说 //block starts while(m3.find()) { // System.out.println(m3.group()); patit = m3.group().replace("(54)", " "); patit = patit.trim();

如果语句块在特定的时间间隔内没有完成,我想跳过它

比如说

//block starts 

   while(m3.find())
                {
                 // System.out.println(m3.group());
                    patit = m3.group().replace("(54)", " ");
                    patit = patit.trim();
                     System.out.println("m3");
                }

                while(m4.find() )
                {
                //  System.out.println(m4.group());
                    patno = m4.group().replace("Patent No.: ", " ");
                    patno = patno.replace("Patent No: ", " ");
                    patno = patno.replace("Patent", " ");
                    patno = patno.replace("No.:", " ");
                    patno = patno.replace("No:", " ");
                    patno = patno.replace("Number: ", " ");
                    patno = patno.replace("Number.: ", " ");
                    patno =  patno.trim();
                     System.out.println("m4");
                }
//block ends
在上面的块中,如果块需要20秒以上才能完成,则必须发出“continue;”语句(跳过此处未给出的for循环)


如何解决这个问题?

< P>你可能想考虑把这个块放在一个单独的线程中运行。如果您可以将该功能重构为实现Runnable的单独类,请让该类在线程中运行,并使用名为isCompleted()的方法。然后,调用新类的类可以执行类似的操作(我只是从内存开始,没有尝试编译或运行它,如果有任何错误,非常抱歉):

YourNewClass otherObject=newyourNewClass();
线程t=新线程(其他对象);
t、 start();
int睡眠时间=1000;
int timeLimit=20000;
而(!otherObject.isCompleted()&&time
这样,如果otherObject完成或经过20秒,while循环将退出。如果20秒过去了,它仍然在运行,那么就对它调用stop()方法


当然,需要注意的是,根据官方Java文档,线程调度在技术上没有保证,因此线程调度程序可以在返回到上面的thread.sleep(sleepTime)之前运行otherObject的run()方法,但如果run()方法花费的时间超过20秒,则不太可能。在newclass.run()的开头执行Thread.sleep(100)可以降低这种可能性,这使得线程调度程序很有可能返回到上面的代码并启动while循环。

更好地确保它不会花费20秒。在大多数情况下,它不应该花费几分之一秒的时间。在开始时启动计时器,它会在结束时设置一个布尔值。并将条件更改为while(find&&!lester20seconds),我将在一个单独的线程中执行它,20秒后我将终止该线程。
YourNewClass otherObject = new YourNewClass();
Thread t = new Thread(otherObject);
t.start();
int sleepTime = 1000;
int timeLimit = 20000;
while(!otherObject.isCompleted() && time < timeLimit) {
    try {
        Thread.sleep(sleepTime);
    } catch(InterruptedException e) {
        //your error handling code
    }
    time += sleepTime;
}
if(!otherObject.isCompleted()) {
    otherObject.stop();
}