2016-02-27 75 views
0

我試圖在JUnit內部運行兩個線程。以下代碼將由幾個JUnit測試調用。JUnit使用Java中的靜態變量運行線程

我想在結果不爲空時停止兩個線程。我該怎麼處理它?問題是多個JUnit測試共享相同的String結果對象,並且不知何故,此代碼被先前的測試阻塞。問題在於,當另一個測試調用此方法時,結果將分配給null,並且以前的測試會在while(true)循環中阻塞。

static String result = null; 

public static synchronized String remoteClogTailDir(final int maxRetry, String hostName, 
     final String identifier, final String remoteClogDirPaths, final String whichKeyValue) { 

    result = null; 
    final String[] hosts = hostName.split(","); 
    if(hosts != null && hosts.length == 2){ 
     Thread t1 = null; 
     Thread t2 = null; 
     t1 = new Thread(new Runnable(){ 
      @Override 
      public void run(){ 
       String resultOfThread = null; 
       resultOfThread = remoteClogTailDir(maxRetry, hosts[0].trim(), identifier, null, 
         remoteClogDirPaths, false, whichKeyValue); 
       if(result == null && resultOfThread != null){ 
        result = resultOfThread; 
       } 
      } 
     }); 

     t2 = new Thread(new Runnable(){ 
      @Override 
      public void run(){ 
       String resultOfThread = null; 
       resultOfThread = remoteClogTailDir(maxRetry, hosts[1].trim(), identifier, null, 
         remoteClogDirPaths, false, whichKeyValue); 
       if(result == null && resultOfThread != null){ 
        result = resultOfThread; 
       } 
      } 
     }); 

     t1.start(); 
     t2.start(); 

     while(true){ 
      if(result != null){ 
       t1.interrupt(); 
       t2.interrupt(); 
       return result; 
      } 
     } 
    }else{ 
     return remoteClogTailDir(maxRetry, hostName, identifier, null, 
       remoteClogDirPaths, false, whichKeyValue); 
    } 
} 

回答

0

如果我理解正確,您想要並行執行多個搜索,並完成第一個搜索。你不應該使用靜態屬性。

你可以使用一個ExecutorCompletionService這樣的任務:

Executor executor = Executors.newCachedThreadPool(); 
CompletionService<String> ecs = new ExecutorCompletionService<String>(executor); 
List<Future<String>> futures = new ArrayList<Future<String>>(); 
try { 
    futures.add(ecs.submit(search1)); 
    futures.add(ecs.submit(search2)); 

    for (int i = 0; i < futures.size(); ++i) { 
    String result = ecs.take().get(); 
    if (result != null) { 
     return result; 
    } 
    } 
} finally { 
    for (Future<String> f : futures) { 
    f.cancel(true); 
    } 
} 
executor.shutdownNow(); 

與搜索1或搜索2一個簡單的可贖回:

Callable<String> search1 = new Callable<String() { 
    public String call() { 
    return remoteClogTailDir(...) 
    } 
} 
+0

哇,這一個工程!謝謝!!!!!對於測試用例在兩臺遠程服務器中搜索文件是正確的。如果在任一服務器中找到文件,則兩個線程將停止,並且該方法將返回文件內容。 –

+0

@YiZhao如果我可以幫你,不要忘了接受這個答案;-) –

+0

接受,謝謝:) –