• Selenium Video Tutorials

Selenium WebDriver - 线程保护



ThreadGuard 类仅适用于 Java 绑定。它用于确保驱动程序从其起源的同一线程调用。在并行模式下运行测试时会遇到多线程问题,而且这些问题有时不容易调试并且难以找到错误的根本原因。借助 ThreadGuard 包装器,我们可以避免这些问题并在适当的时间生成正确的异常。

示例

public class DriverParallel { //Thread main (id 1) created this driver private WebDriver pDriver = ThreadGuard.protect(new EdgeDriver()); //Thread-1 (id 14) is calling the same driver resulting in error Runnable run1 = () -> { protectedDriver.get("https://tutorialspoint.com/selenium/practice/accordion.php"); }; Thread thread1 = new Thread(run1); void runThreads(){ thread1.start(); } public static void main(String[] args) { new DriverClash().runThreads(); } }

以上代码将引发异常。在这里,pDriver 将在主线程中创建。Runnable 类用于引入新进程和新线程。它们都将遇到问题,因为主线程在其内存中缺少 pDriver。因此,threadGuard.protect 将引发异常。

因此,在本教程中,我们讨论了使用 Selenium Webdriver 的 ThreadGuard。

广告