2015-10-07 89 views
1

最近我鑽研了線程的黑暗藝術,我學會了如何創建它們以及何時使用它們以及何時不使用它們。但是當我試圖學習如何溝通它們時,我發現管道是你用來做的。我有一個對象,它是我創建的一個類的實例「,但管道似乎只能發送字節數組或整數。我不會能夠使用類似於對象流的東西來將我的對象發送給另一個線程,但是我的網上衝浪已經非常糟糕,我迷路了。所以我猜想唯一要做的就是轉向堆棧溢出,看看有沒有人可以幫忙。感謝您提前的幫助。與兩個線程通信時,我必須使用管道嗎?

+0

退房[類似](http://stackoverflow.com/questions/2170520/inter-thread-communication-in-java)[問題](http://stackoverflow.com/questions/9242204/線程間通信)替代選項 –

+0

也有類似的問題,但我找不到一個有我的答案或問我問的問題。 – NicholasLupo

+0

你從哪裏得到管道?這似乎離開了左邊的領域。你是指不同的過程? – matt

回答

5

您應該使用BlockingQueue的實現之一。

我最常使用ArrayBlockingQueue,因爲它允許我限制解決方案的內存佔用。 A LinkedBlockingDeque可用於無限大小,但請確保您不能超載內存。

這裏有兩個線程使用ArrayBlockingQueue來溝通自己。

public class TwoThreads { 

    public static void main(String args[]) throws InterruptedException { 
     System.out.println("TwoThreads:Test"); 
     new TwoThreads().test(); 
    } 

    // The end of the list. 
    private static final Integer End = -1; 

    static class Producer implements Runnable { 

     final BlockingQueue<Integer> queue; 

     public Producer(BlockingQueue<Integer> queue) { 
      this.queue = queue; 
     } 

     @Override 
     public void run() { 
      try { 
       for (int i = 0; i < 1000; i++) { 
        queue.add(i); 
        Thread.sleep(1); 
       } 
       // Finish the queue. 
       queue.add(End); 
      } catch (InterruptedException ex) { 
       // Just exit. 
      } 
     } 

    } 

    static class Consumer implements Runnable { 

     final BlockingQueue<Integer> queue; 

     public Consumer(BlockingQueue<Integer> queue) { 
      this.queue = queue; 
     } 

     @Override 
     public void run() { 
      boolean ended = false; 
      while (!ended) { 
       try { 
        Integer i = queue.take(); 
        ended = i == End; 
        System.out.println(i); 
       } catch (InterruptedException ex) { 
        ended = true; 
       } 
      } 
     } 

    } 

    public void test() throws InterruptedException { 
     BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(); 
     Thread pt = new Thread(new Producer(queue)); 
     Thread ct = new Thread(new Consumer(queue)); 
     // Start it all going. 
     pt.start(); 
     ct.start(); 
     // Wait for it to finish. 
     pt.join(); 
     ct.join(); 
    } 

} 
+0

這正是我所期待的。這個編程的東西,我只是繼續學習!謝謝! – NicholasLupo