排队完全错误,与多个使用者,生产者一起工作

詹姆斯·赖采夫(James Raitsev):

我想模拟以下情况:多个使用者,生产者线程正在将某些数据修改为

建立

    BlockingQueue<String> q1 = new SynchronousQueue<String>();
    BlockingQueue<String> q2 = new SynchronousQueue<String>();

    Producer dataProducer = new Producer(q1); // publish to q1

    Filter1 filter1 = new Filter1(q1, q2);    // read from q1, publish to q2
    Filter2 filter2 = new Filter2(q2);        // read from q2

    new Thread(dataProducer, "Producer-Thread").start();
    new Thread(filter1, "Filter1-Thread").start();
    new Thread(filter2, "Filter2-Thread").start();

制片人

public void run() {
    try {
        while (true) {
            this.q.put(saySomething());
        }
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}

public String saySomething() {
    return "Something";
}

过滤器1

public void run() {
    try {
        while (true) {
            consume(qIn.take());
        }
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}

private void consume(String take) {
    //Modify data according to some rules
    String newData = take.replace("m", "-");
    produce(newData);
}

private void produce(String newData) {
    // put new data in queue out
    qOut.add(newData);                   // <-- Stacktrace points here
}

过滤器2

public void run() {
    try {
        while (true) {
            consume(qIn.take());
        }
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}

private void consume(String s) {
    System.out.println("Something became: " + s);
}

因此,回顾一下:生产者将某些内容放入队列中,从中读取过滤器1。它修改数据并将其发布到过滤器2读取的另一个队列中。过滤器2打印最终数据。

这段代码失败了

Exception in thread "Thread-2" java.lang.IllegalStateException: Queue full

你能帮我理解为什么吗?

约翰·温特:

您应该使用put()而不是add()SynchronousQueue始终是满空的,没有深度。put()将告诉队列挂起该线程,直到有另一个线程将元素移出队列。

add()仅当有线程在等待时,方法才会成功;如果没有线程在等待,您将获得“队列已满”异常。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

生产者是一个主线程,有n个使用者在无限循环中运行,所有使用者都在阻塞队列上工作。如何关机

生产者使用者-使用Executors.newFixedThreadPool

IntegrationMBeanExporter.stopActiveComponents()与gcp发布/订阅生产者一起抛出了InterruptedExceptions负载

与多个使用者一起使用Amazon SQS

从同一JVM运行kafka使用者和生产者时生产者速度较慢

与多个使用者一起使用BlockingCollection

如何与其他语言的TAP生产者一起使用Perl的“证明”?

在Linux上使用Python 3.x的多处理生产者使用者

无法在使用者线程中使用JNI的生产者-使用者程序中捕获SIGINT信号

具有多个使用者的生产者使用notify()失败

将多个使用者与CosmosDB更改提要一起使用

Python多线程生产者使用者模式

使用者和生产者失败,并显示错误:“在读取响应之前,已断开与0的连接”

生产者配置的request.timeout.ms和代理配置的request.timeout.ms如何一起使用

Java生产者使用者停止使用者线程

Java生产者使用者IllegalMonitorStateException

与一个生产者和多个消费者一起使用Queue是否安全?

C#BlockingCollection生产者使用者,而不阻塞使用者线程

具有多个选择线程的MySQL生产者使用者

Java-多队列生产者使用者

使用sleep()时,生产者使用者(使用监视器)代码无法正常工作?

C#中的生产者使用者,具有多个(并行)使用者,并且没有TPL数据流

在生产者/消费者模式中,如何杀死使用者线程?

多个生产者使用者在C#中同时工作

C-Pthreads,一个使用者,多个生产者同步

来自生产者使用者队列的另一个类的线程

Rabbitmq生产者(symfony 3)和使用者错误(NodeJs)

如何在activeMQ中使用多个生产者和一个消费者?

生产者端排队