【问题标题】:When communicating with two threads do I have to use pipes?当与两个线程通信时,我必须使用管道吗?
【发布时间】:2015-10-07 07:13:09
【问题描述】:

最近我深入研究了 Threads 的黑暗艺术,我了解了如何创建它们以及何时使用它们以及何时不使用它们。但是当我试图学习如何在他们之间进行交流时;我发现管道是你用来做的。我有一个对象,它是我创建的类之一的实例,但管道似乎只能发送字节数组或整数。我不能使用对象流之类的东西将我的对象发送到另一个线程,但是我的互联网冲浪变得非常糟糕,我迷路了。所以我猜唯一要做的就是转向 Stack Overflow,看看是否有人可以提供帮助。提前感谢您的帮助。

【问题讨论】:

  • 查看similar questions 了解替代选项
  • 有类似的问题,但我找不到有我的答案或提出我提出的问题的问题。
  • 你从哪里得到管道?这似乎超出了左场。您指的是不同的流程吗?
  • pipoutputstreams 和 pipeinputstreams
  • 曾经使用 bytes[] 与线程通信。你一定在考虑 unix 管道?

标签: java multithreading


【解决方案1】:

您应该使用BlockingQueue 的实现之一。

我最常使用ArrayBlockingQueue,因为它允许我限制解决方案的内存占用。 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();
    }

}

【讨论】:

  • 这正是我想要的。这个编程的东西,我一直在学习!!!谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 1970-01-01
相关资源
最近更新 更多