gpt4 book ai didi

java - 多线程中面临的问题

转载 作者:行者123 更新时间:2023-11-29 03:01:34 24 4
gpt4 key购买 nike

我写了一段代码,它将从主类启动固定数量的线程。下面的功能只是其中的一部分。所有线程都会来到这个方法。我给了线程名称,如 USER1、USER2 等。

我的要求是,在这个方法中,在 driver=WebDriver....... 语句之后,我的所有线程都应该等待,直到它们都获得驱动程序。我知道我们可以加入。但无法在这里实现。有人可以指导

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 ;
}
}
}

最佳答案

您可以使用 CountDownLatch。创建一个 CountDownLatch 并使用 fixed number of thread 值并在获取 WebDriver 实例后调用 countdown() > 然后调用 await() 等待所有线程到达那里。

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 ;
}
}
}

关于java - 多线程中面临的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34523360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com