面对多线程中的问题

时间:2015-12-30 05:20:00

标签: java multithreading

我编写了一个代码,它将从主类中启动固定数量的线程。下面的功能只是其中的一部分。所有线程都将使用此方法。我给了像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 ;
            }
        }
    }

2 个答案:

答案 0 :(得分:4)

您可以使用CountDownLatch。创建CountDownLatch值为fixed number of thread并在获得countdown()的实例后调用WebDriver,然后调用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 ;
    }
  }
}

答案 1 :(得分:0)

首先:如果所有人都等待所有人获得驱动程序,那么当一个人无法获得驱动程序时你会遇到问题。

为了让所有人都相互等待(我认为我实际上并没有这样做,但这是一个建议)。既然你知道线程的数量,你可以做类似的事情:

  • 线程获取驱动程序
  • 线程调用同步方法(一次只能运行1个线程),将计数器递减1(初始化为线程数)。
  • 线程产量。
  • 线程再次运行,调用一个方法来检查计数器是否已达到0。
  • 答:计数器不是0,线程收益。
  • B:Counter为0,线程继续工作。