2015-12-30 50 views
1

我已經寫了一個代碼,它將從主類中啓動固定的線程數。下面的功能只是它的一部分。所有線程都會採用這種方法。我給了線程名稱像USER1,USER2等面對多線程中的問題

我的要求是,在這個方法後,驅動程序= 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 ; 
      } 
     } 
    } 
+0

那麼,你必須阻止,直到發生某些事件?爲什麼不使用某種類型的鎖?看看[鎖定對象](https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html) – MadProgrammer

+0

我認爲你需要另一個類來監督你​​的線程。他們應該註冊自己到這個類(簽入),然後結賬並用Thread.sleep()睡着。只要所有的線程都結賬,通知他們所有的人將其喚醒。 –

回答

4

您可以使用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 ; 
    } 
    } 
} 
+2

當驅動程序調用失敗時,這會造成死鎖。 –

+1

在發生特定異常時,應該減少'catch'塊中的'countDownLatch' –

+1

等待所有人都獲得驅動程序,如果只是在出現故障時繼續執行,那麼這將毫無意義。中止應用似乎更合理。但是OP沒有說明應該做什麼,所以把它留給他們。但是,是的,捕捉是處理這種情況的好地方。 –

0

首先:如果所有人都等待得到驅動程序,那麼當你無法獲得驅動程序時你有問題。

爲了讓所有人都相互等待(我不認爲我曾經這樣做過,但這裏有一個建議)。既然你知道線程的數量,可以使這樣的:

  • 線程獲取驅動
  • 線程調用遞減1計數器的同步方式(僅1個線程可以同時運行)(初始化到線程數)。
  • 線程收益。
  • 線程再次運行,調用一個方法來檢查計數器是否達到0.
  • 答:計數器不是0,線程產量。 B:計數器爲0,線程繼續工作。