I have a couple suggestions for you.
1: Naming Convention
In your post, you said:
"...in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle."
This is not a very good approach and here's why: let's say that you have two WebDrivers, each named "driverX". You need the first driver to go to "www.google.com", and you need the second driver to go to "www.yahoo.com". As such, your code looks like this:
driverX.get("www.google.com");
driverX.get("www.yahoo.com");
This becomes a problem, as instead of telling the second WebDriver to go to Yahoo, you have actually rerouted the first WebDriver from Google to Yahoo.
What is the solution to this problem? Name each of your WebDrivers with a unique name (googleDriver
or yahooDriver
for example). Then, your code will look like this and you should not have any conflicts:
googleDriver.get("www.google.com");
yahooDriver.get("www.yahoo.com");
2: WebDriver Grouping
Now that we have each of your WebDrivers with a unique name, we are able to reference them individually. This is great, however, some applications require that we reference several of them at once. This is where ArrayLists can come in. In the code below, I used an ArrayList to solve your original question.
ArrayList<WebDriver> activeDrivers = new ArrayList<>();
activeDrivers.add(googleDriver);
activeDrivers.add(yahooDriver);
for(WebDriver driver : activeDrivers){
if(driver.getCurrentUrl().equals("Some predefined exit page"){
driver.quit();
}
}
Feel free to leave a comment if you still do not understand or if you have any questions.