ThreadGuard
此类仅在 Java 绑定中可用
ThreadGuard 检查驱动程序是否仅从创建它的同一线程调用。线程问题,尤其是在并行运行测试时,可能会出现神秘且难以诊断的错误。使用此包装器可以防止此类错误,并在发生时引发异常。
以下示例模拟了线程冲突
public class DriverClash {
//thread main (id 1) created this driver
private WebDriver protectedDriver = ThreadGuard.protect(new ChromeDriver());
static {
System.setProperty("webdriver.chrome.driver", "<Set path to your Chromedriver>");
}
//Thread-1 (id 24) is calling the same driver causing the clash to happen
Runnable r1 = () -> {protectedDriver.get("https://seleniumcn.cn");};
Thread thr1 = new Thread(r1);
void runThreads(){
thr1.start();
}
public static void main(String[] args) {
new DriverClash().runThreads();
}
}
下面显示的结果
Exception in thread "Thread-1" org.openqa.selenium.WebDriverException:
Thread safety error; this instance of WebDriver was constructed
on thread main (id 1)and is being accessed by thread Thread-1 (id 24)
This is not permitted and *will* cause undefined behaviour
如示例所示
protectedDriver
将在主线程中创建- 我们使用 Java
Runnable
来启动新进程,并使用新的Thread
来运行该进程 - 两个
Thread
将会冲突,因为主线程的内存中没有protectedDriver
。 ThreadGuard.protect
将抛出异常。
注意
这不能替代在并行运行时使用 ThreadLocal
管理驱动程序的需求。