在 java 中,我尝试使用下面的代码使用简单的等待和 notifyAll() 方法编写生产者和消费者实现。它运行了几秒钟,然后挂起。任何想法如何解决这个问题。
import java.util.ArrayDeque;
import java.util.Queue;
public class Prod_consumer {
static Queue<String> q = new ArrayDeque(10);
static class Producer implements Runnable {
public void run() {
while (true) {
if (q.size() == 10) {
synchronized (q) {
try {
System.out.println("Q is full so waiting");
q.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
synchronized (q) {
String st = System.currentTimeMillis() + "";
q.add(st);
q.notifyAll();
}
}
}
}
static class Consumer implements Runnable {
public void run() {
while (true) {
if (q.isEmpty()) {
synchronized(q) {
try {
System.out.println("Q is empty so waiting ");
q.wait();
}catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
synchronized(q) {
System.out.println(q.remove());
q.notifyAll();
}
}
}
}
public static void main(String args[]) {
Thread consumer = new Thread(new Consumer());
Thread consumer2 = new Thread(new Consumer());
Thread producer = new Thread(new Producer());
producer.start();
consumer.start();
consumer2.start();
}
}