【发布时间】:2020-03-07 14:38:57
【问题描述】:
我编写了以下显示生产者消费者模式的 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();
}
}
【问题讨论】:
标签: java multithreading