简体   繁体   中英

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). 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.

// 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?

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. 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:

  • thread A: does webDriver.switchTo()
  • thread B: does webDriver.switchTo()
  • thread A: prints the page title

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. But that basically serializes your testing.

Long story short: that webDriver object has internal state. 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. Beyond that, for an idea how to do it differently, in a way that matches how selenium "thinks" about parallel tests, see here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM