在 java 类中,我有一个方法有时需要很长时间才能执行。也许它卡在那个方法流程中。我想要的是,如果方法没有在特定时间完成,程序应该退出该方法并继续流程的其余部分。
请告诉我有什么办法可以处理这种情况。
最佳答案
您必须使用线程才能实现此目的。线程是无害的:) 下面的示例运行一段代码 10 秒,然后结束它。
public class Test {
public static void main(String args[])
throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("0");
method();
}
});
thread.start();
long endTimeMillis = System.currentTimeMillis() + 10000;
while (thread.isAlive()) {
if (System.currentTimeMillis() > endTimeMillis) {
System.out.println("1");
break;
}
try {
System.out.println("2");
Thread.sleep(500);
}
catch (InterruptedException t) {}
}
}
static void method() {
long endTimeMillis = System.currentTimeMillis() + 10000;
while (true) {
// method logic
System.out.println("3");
if (System.currentTimeMillis() > endTimeMillis) {
// do some clean-up
System.out.println("4");
return;
}
}
}
}
关于java - java中的超时方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8982420/