2015-10-07 53 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