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);
}
}
哇,這一個工程!謝謝!!!!!對於測試用例在兩臺遠程服務器中搜索文件是正確的。如果在任一服務器中找到文件,則兩個線程將停止,並且該方法將返回文件內容。 –
@YiZhao如果我可以幫你,不要忘了接受這個答案;-) –
接受,謝謝:) –