我编写了下面的java代码,它显示了生产者消费者模式。我想知道生产者消费者模式中如何发生死锁和饥饿。我在互联网上搜索了这个查询。但是我找不到合适的文章来清楚地解释生产者消费者模式中如何发生死锁和饥饿。
public class InterThreadCommunication_Producer_Consumer {
static Queue<Integer> queue = new LinkedList<>();
static int size = 4;
public static void produce() throws InterruptedException {
int value = 0;
while(true) {
synchronized (queue) {
while(queue.size() >= size) {
queue.wait();
}
queue.add(value);
System.out.println("Produced" + value);
value++;
queue.notify();
Thread.sleep(1000);
}
}
}
public static void consume() throws InterruptedException {
while(true) {
synchronized (queue) {
while(queue.isEmpty()) {
queue.wait();
}
int value = queue.poll();
System.out.println("Consume" + value);
queue.notify();
Thread.sleep(1000);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread producerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producerThread.start();
consumerThread.start();
producerThread.join();
consumerThread.join();
}
}
最佳答案
有僵局吗?
死锁并非特定于生产者-消费者等协作模式,而是来自锁定模式。有了一把锁,您就安全了。
对于死锁,您至少需要两个锁和两个线程:
Time 0 1
Thread 1: Lock(A) Wait-Lock(B)
Thread 2: Lock(B) Wait-Lock(A)
如您所见,在时间 0 时,两个线程都在获取两个资源的锁。在时间 1,他们互相等待,没有继续进行的非协作可能性。
通知政策
来看您的示例:您在具有相同通知(queue
对象)的两个不同线程中使用 wait()
和 notify()
,这表明该通知不属于明确事件(即 queue
非空)。这会导致问题,特别是当您使用两个以上线程时。您将同一通知重复用于:
- 可用数据
- 队列空间可用
通知您在不同对象中等待的条件。我还建议缩小关键部分(同步部分)的范围。
关于java - java生产者消费者模式如何出现死锁和饥饿问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578655/