当条件被叠加时,如何在Java中中断“while”循环
我有以下Java代码:
while( someMethod() ) {
//do something
}
someMethod()使用正则表达式解析某些文本。当文件太大时,可能会花费太多时间,我更喜欢将其破坏。 如果someMethod()耗尽了时间,我如何设置超时并中断循环
谢谢大家!
重要提示:someMethod()不是我的代码,我无法更改它
你可以在下面搜索框中键入要查询的问题!
我有以下Java代码:
while( someMethod() ) {
//do something
}
someMethod()使用正则表达式解析某些文本。当文件太大时,可能会花费太多时间,我更喜欢将其破坏。 如果someMethod()耗尽了时间,我如何设置超时并中断循环
谢谢大家!
重要提示:someMethod()不是我的代码,我无法更改它
# 1 楼答案
一种方法是创建一个调用该方法的新线程,然后调用线程。在主线程中加入(长超时)
在你的主课上:
# 2 楼答案
您必须为该调用包含一个单独的线程
这将在指定的最长时间段内阻塞,并抛出一个
TimeoutException
oherwise,这将中断循环。您可以捕获异常请注意,这并不是很优雅,因为对该方法的调用将保持不变,并可能永远占用该线程。如果方法不可中断,就没有安全的解决方法
# 3 楼答案
实现someMethod,使其在达到指定限制时返回false:
这样,如果某个方法在其核心逻辑中陷入无限循环,那么while将退出
# 4 楼答案
完整的应用程序包括导入: