我创建了自己的队列。
队列.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/