如何解决如何在 Java 中停止 currentThread?
我正在使用 TestNg 运行并行测试,我想在脚本中的某些点停止/终止线程。这个脚本有很多层,所以简单地抛出异常一直回到 main() 并不是我的最佳途径。
thread.stop()
对我有用,但它已被弃用,所以我宁愿不使用它,而 thread.interrupt() 对我不起作用,因为如果线程被中断,我将不得不检查许多不同的地方.这是我的意思的一个简短的虚构示例:
driverexec.navigateTo("http://www.google.com");
xpath= "//input[@name='q111']";
driverexec.typeByXpath("type search",xpath,"gorillas");
System.out.println("gojng again");
xpath= "//input[@name='btnK']";
driverexec.clickByXpath("search google",xpath);
现在,每个 driverexec
函数都可能失败,我为此设置了一个失败函数。所以基本上每次我的 failure()
函数被调用时,我都想 stop
当前线程。
所有看到如果中断会导致我不得不放置行的示例:
if (thread.interrupted()){
}
在我的失败函数内部或每次函数调用之后。但即使我把它放在我的失败函数中,这也只是设置了标志。我怎样才能真正停止它?
解决方法
您可以从内部杀死线程,这意味着抛出一个您永远不会捕获的 elements.eq(i).attr("custom-attr","analytics-purposes-only" +
elements.eq(i)..text().trim());
或 Exception
,并且它只会向上传播到调用堆栈:
Error
您也不必担心您的 public void failure() {
// as you're using a test,an assertion error may be a suitable option
throw new AssertionError("Test failure");
}
方法会受到此影响,因为除 main
-Thread
之外的 main
的异常不会一路向上传播。