Here is an example of a Java program that implements the Producer-Consumer problem using the wait and notify methods:
import java.util.LinkedList;
public class ProducerConsumer {
private LinkedList<Integer> buffer;
private int capacity;
public ProducerConsumer(int capacity) {
this.buffer = new LinkedList<>();
this.capacity = capacity;
}
public void produce(int value) throws InterruptedException {
synchronized (this) {
while (buffer.size() == capacity) {
wait();
}
buffer.add(value);
System.out.println("Produced " + value);
notify();
}
}
public int consume() throws InterruptedException {
synchronized (this) {
while (buffer.isEmpty()) {
wait();
}
int value = buffer.removeFirst();
System.out.println("Consumed " + value);
notify();
return value;
}
}
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer(5);
Runnable producer = () -> {
try {
for (int i = 0; i < 10; i++) {
pc.produce(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable consumer = () -> {
try {
for (int i = 0; i < 10; i++) {
pc.consume();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}
The ProducerConsumer class contains a buffer (implemented as a linked list) and its capacity, as well as produce and consume methods. The produce method adds an item to the buffer if it is not full. If the buffer is full, it waits until a consumer takes an item. The consume method removes an item from the buffer if it is not empty. If the buffer is empty, it waits until a producer adds an item. The main method starts two threads, one for producing and one for consuming, and each thread runs 10 times.
No comments:
Post a Comment