Reputation: 97
I have written a code where it will launch the fixed number of threads from the main class. Below function is just a part of it . All threads will come to this method. I have given thread names like USER1, USER2 etc.
My requirement is that in this method after driver=WebDriver....... statement all of my threads should wait until they all get the driver. I know we can join . But unable to implement here . Can someone please guide
private void testSuitLogin(String driverType){
try{
System.out.println(Thread.currentThread().getName()+" Start Time "+System.currentTimeMillis());
driver = WebDriverFactory.getDriver(driverType);
System.out.println(Thread.currentThread().getName()+" End Time "+System.currentTimeMillis());
homePage();
googleSignIn();
driver.quit();
}
catch(Exception e){
if(driver==null)
{
totalNumberOfUsers--;
return ;
}
}
}
Upvotes: 1
Views: 65
Reputation: 13402
You can use the CountDownLatch
. Create a CountDownLatch
with a fixed number of thread
value and call countdown()
after you get the instance of the WebDriver
and then call await()
to wait until all the threads arrive there.
CountDownLatch countDownLatch = new CountDownLatch(fixedNumber);
private void testSuitLogin(String driverType){
try{
System.out.println(Thread.currentThread().getName()+" Start Time "+System.currentTimeMillis());
driver = WebDriverFactory.getDriver(driverType);
countDownLatch.countDown(); // decreases the value of latch by 1 in each call.
countDownLatch.await(); //It will wait until value of the latch reaches zero.
System.out.println(Thread.currentThread().getName()+" End Time "+System.currentTimeMillis());
homePage();
googleSignIn();
driver.quit();
}
catch(Exception e){
if(driver==null)
{
countDownLatch.countDown();
totalNumberOfUsers--;
return ;
}
}
}
Upvotes: 4
Reputation: 171
First: If all wait for all to get the driver, then you have a problem when one fails to get the driver.
In order to have all wait for each other (I don't think I have actually ever done that, but here is a suggestion). Since you know the number of threads, you can make something like:
Upvotes: 0