2014-07-17 112 views
4

我有一個需要由三方(線程,可以說)填充的列表。我正在使用循環屏障來實現此功能。一切工作正常,但我無法使用結果列表,而不會導致強迫睡眠。下面是代碼:java中的循環屏障

public class Test{ 

List<Integer> item = new Vector<Integer>(); 

public void returnTheList(){ 
     CyclicBarrier cb = new CyclicBarrier(3, new Runnable() { 

       @Override 
       public void run() { 

        System.out.println("All parties are arrived at barrier, lets play -- : " + CyclicBarrierTest.getTheList().size()); 
        //Here I am able to access my resulted list 

       } 
      }); 


      CyclicBarrierTest sw1 = new CyclicBarrierTest(cb, new ZetaCode(1500), s); 
      CyclicBarrierTest sw2 = new CyclicBarrierTest(cb, new ZetaCode(1500),s); 
      CyclicBarrierTest sw3 = new CyclicBarrierTest(cb, new ZetaCode(1500),s); 
      Thread th1 = new Thread(sw1, "ZetaCode1"); 
      Thread th2 = new Thread(sw2, "ZetaCode2"); 
      Thread th3 = new Thread(sw3, "ZetaCode3"); 
      th1.start(); 
      th2.start(); 
      th3.start(); 

    } 

public static void main(String args[]){ 
    System.out.println("asdfasd"); 
    Test test = new Test(); 
    //ActionClass ac = new ActionClass(); 
    test.returnTheList(); 
    System.out.println("Inside the main method...size of the final list : " +test.item.size()); 
} 

下面是我的CyclicBrrierTest類:

public class CyclicBarrierTest implements Runnable{ 

private CyclicBarrier barrier; 
private Object obj; 
static volatile String s = ""; 
volatile List<Integer> finalIntList = new Vector<Integer>(); 

public CyclicBarrierTest(CyclicBarrier barrier, Object obj, String s){ 
    this.barrier = barrier; 
    this.obj = obj; 
} 

@Override 
public void run(){ 
    try{ 
     System.out.println(Thread.currentThread().getName() + " is waiting on barrier and s is now : " + finalIntList.size()); 
     ZetaCode simple = (ZetaCode)obj; 

     finalIntList.addAll(simple.getTheItemList()); 
     barrier.await(); 

     System.out.println(Thread.currentThread().getName() + " has crossed the barrier"); 

    }catch(InterruptedException ex){ 
     System.out.println("Error.." + ex.getMessage()); 

    }catch(Exception e){ 
     System.out.println("Error.." + e.getMessage()); 
    } 
} 
    public List<Integer> getTheList(){ 
    return finalIntList; 
} 

所以,如果我沒有給任何延遲在我的主要方法print語句運行這段代碼給了我,我的列表的長度零,然而,在給予適當的睡眠後,它給了我預期的輸出。我想實現相同,沒有任何延遲。任何幫助,將不勝感激。 在此先感謝。

回答

5

看來你想在這裏使用CountDownLatch而不是CyclicBarrierCyclicBarrier完全按照預期工作 - 您的主要方法並不是等待它被所有3個線程觸發。當你給它一個睡眠聲明時,其他3個線程恰好在main再次醒來之前完成。

A CyclicBarrier當您需要N工作人員在繼續操作之前都達到同一個「檢查點」時非常有用,並且工人本身是唯一關心的人。但是,這裏有N + 1用戶,main線程,他們想知道他們什麼時候全部完成,CyclicBarrier不支持該用例。

注意,當然你也可以使用它們兩個。

+0

事實上,CyclicBarrier確實符合我最初的要求。後來我遇到了這個問題。應該看到它來了。無論如何謝謝你的快速反應:) – viks1010

+0

這是關於軟件的奇妙和可怕的事情 - 它改變:) – torquestomp