java - 为什么我的生产者消费者程序被阻塞?

标签 java multithreading producer-consumer

我创建了自己的队列。

队列.java

public class MyQueue {

    private int size;

    private Queue<String> q;

    public MyQueue(int size ,Queue<String> queue) {
    this.size = size;
    this.q = queue;

    }

    //getter and setter    

    public synchronized void putTail(String s) {

System.out.println(this.size); // It should print 0, 1,2

          while (q.size() != size) {

             try {
                wait();
             }
             catch (InterruptedException e) {
             }
          }
          Date d = new Date();

          q.add(d.toString());

          notifyAll();

       }

}

MyProducer.java

导入com.conpro.MyQueue;

public class MyProducer  implements Runnable {

    private final MyQueue queue;

    private final int size; 

    MyProducer(int size,MyQueue q) { this.queue = q; this.size = size; }


    @Override
    public void run() 
    {
        queue.putTail(String.valueOf(Math.random()));
    }

}

MyTest.java

public class MyTest {

    public static void main(String[] args) {

        Queue q = new PriorityQueue<String>();
        MyQueue mq = new MyQueue(3,q);

         MyProducer p = new MyProducer(3,mq);
         MyProducer p1 = new MyProducer(3,mq);
         MyProducer p2 = new MyProducer(3,mq);
         new Thread(p).start();
         new Thread(p1).start();
         new Thread(p2).start();

    }

}

现在我在这里创建了 3 个 Producer 。 所以执行完这三行后,队列应该已满。

输出应该是:

0
1
2

但它只打印0

为什么?

P.S:我只编写了生产者代码,因为我还没有到达那里。

最佳答案

由于putTail()同步的,所以三个线程中只有一个可以进入。然后,该线程永远位于 while (q.size() != size) 循环内,而其他两个线程仍然无法进入该方法。

关于java - 为什么我的生产者消费者程序被阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18165681/

相关文章:

java - 在返回 Cursor 的函数中关闭 Cursor

java - 如何模拟并行运行的线程之间的竞争?

java - Java中使用wait()和notify()的生产者消费者程序

java - libgdx 是否能够同时识别 20 - 30 个手指?

java - 无法在 android studio 中安装或找到 android sdk

java - Jetty:我如何使用 FilterHolder 来处理 "monitor"传入的 HTTP POST 请求内容?

multithreading - Clojure并行计算数组

Linux 每个进程的资源限制——一个深奥的 Red Hat 之谜

c - 如何在没有全局变量的情况下使用线程实现信号量

c++ - 中断或加入后重用 Boost 线程(来自线程池)