[英]Finding a loser thread using Java CountDownLatch
我編寫了一個排序程序,該程序為每個sort
方法調用創建了一個單獨的線程,所有線程均寫入一個共享變量,以說明它們完成了什么類型的排序(字符串,Integers等)。 我使用CountDownLatch
等待所有線程完成並檢索該共享變量以找出失敗者。 我已經運行了代碼,似乎得到了正確的結果,但是由於缺乏Java線程的經驗,我不確定下面程序的有效性。 這可能是一個普遍的問題:以下程序是否存在嚴重錯誤?
public class LatchedSorter {
private SortingType loserType;
private final CountDownLatch stopLatch;
public LatchedSorter(CountDownLatch stopLatch) {
this.stopLatch = stopLatch;
}
public synchronized SortingType getLoserType() {
return this.loserType;
}
public synchronized void setLoserType(SortingType loserType) {
this.loserType = loserType;
}
public <T extends Comparable<? super T>> void sort(final List<T> list, final SortingType type) {
Runnable current = new Runnable() {
public void run() {
Collections.sort(list);
setLoserType(type);
stopLatch.countDown();
}
};
new Thread(current).start();
}
}
而主調用方是這樣的:
public static void main(String args[]){
CountDownLatch cdl = new CountDownLatch(2);
LatchedSorter cs = new LatchedSorter(cdl);
List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();
for(int i=0; i<1000; i++) {
stringList.add(String.valueOf(i));
integerList.add(i);
}
cs.sort(integerList, SortingType.Integers);
cs.sort(stringList, SortingType.Strings);
try {
cdl.await();
System.out.println("Loser thread is: "+cs.getLoserType());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
該程序沒有任何問題,並且永遠不要顯示任何數據或競爭條件。 很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.