[英]Runnable inside for-loop
I want to run a code inside a for-loop in a thread because it almost will do the same but for different pages (with selenium webdriver). 我想在线程的for循环内运行代码,因为它几乎可以执行相同的操作,但适用于不同的页面(使用Selenium Webdriver)。 My Problem is, that my counter variable cannot increase because it must be final... 我的问题是,我的计数器变量无法增加,因为它必须是最终变量。
This is my test code but the variable "tabCount" stays always at a count of i. 这是我的测试代码,但变量“ tabCount”始终保持为i。
// scrape over all tabs and get data in threads
for (int i = 0; i < tabs.size(); i++) {
final int tabCount = i;
Runnable r = () -> {
webDriver.switchTo().window(tabs.get(tabCount));
System.out.println(webDriver.getTitle());
};
threadPool.execute(r);
}
threadPool.shutdown();
try {
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
can anyone help me to do the same operation parallel in each tab of my chromedriver? 有人可以帮助我在chromedriver的每个标签页中并行执行相同的操作吗?
I think you are going down the wrong rabbit hole. 我认为您走错了兔子洞。 Look at your code: 查看您的代码:
webDriver.switchTo().window(tabs.get(tabCount));
System.out.println(webDriver.getTitle());
You want the webDriver to switch to another window. 您希望webDriver 切换到另一个窗口。 And then do something on that tab. 然后在该选项卡上执行某些操作。 But what if there is a context switch of threads between the first and the second line?! 但是,如果第一行和第二行之间存在线程的上下文切换该怎么办?
As in: 如:
webDriver.switchTo()
线程A:是否执行webDriver.switchTo()
webDriver.switchTo()
线程B:是否执行webDriver.switchTo()
Obviously this will lead to race conditions! 显然,这将导致比赛条件! Of course, you could add some sort of locking/synchronizing, so that a thread always switches to the a tab and does its work, without another thread being able to update the webDriver object in the meantime. 当然,您可以添加某种类型的锁定/同步,以便线程始终切换到选项卡并执行其工作,而另一个线程无法同时更新webDriver对象。 But that basically serializes your testing. 但这基本上可以序列化您的测试。
Long story short: that webDriver
object has internal state. 长话短说:该webDriver
对象具有内部状态。 Your approach completely ignores that fact, therefore it is impossible to predict what exactly your code will be doing. 您的方法完全忽略了这一事实,因此无法预测代码将要执行的操作。
A simple fix would be to instantiate one WebDriver instance per thread, as suggested in the comments. 一个简单的解决方法是按照注释中的建议在每个线程中实例化一个WebDriver实例。 Beyond that, for an idea how to do it differently, in a way that matches how selenium "thinks" about parallel tests, see here . 除此之外,有关如何以不同于硒“思考”并行测试的方式的想法,请参见此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.