2011-11-06 28 views
0

我編寫了一個排序程序,爲每個sort方法調用創建一個單獨的線程,所有線程都寫入共享變量以說明它們的排序類型(字符串,整數等)完成。我使用CountDownLatch等待所有線程完成並檢索該共享變量以找出失敗者。我已經運行我的代碼,似乎得到了正確的結果,但是我在Java線程方面的經驗不足,使我不確定以下程序的有效性。這可能是一個普遍的問題:下面的程序有什麼錯誤嗎?使用Java查找輸出線程CountDownLatch

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(); 
     } 
    } 
+0

這很好,但是我不確定你是否真的需要'SortingType'字段的'synchronized'訪問器(或者甚至使它成爲volatile),因爲文檔說在一個線程中, countDown()'*在'await()'成功返回後,在另一個線程中發生行動,這就是你正在做的事情。 –

+0

@BrunoReis謝謝你的回答,我只是看了一眼,我認爲你是對的,因爲賦值運算符是原子的,所以我甚至不需要使setter同步。你對此有何想法? – Abidi

回答

0

沒有什麼錯的程序和不應該顯示任何數據或競爭條件。它非常好。