Here is an example of a Producer Consumer problem using a BlockingQueue in Java:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumer {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);
Thread producer = new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
System.out.println("Producing item: " + i);
queue.put(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumer = new Thread(() -> {
while (true) {
try {
int item = queue.take();
System.out.println("Consuming item: " + item);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}
In this example, the Producer produces items from 0 to 99 and puts them into a BlockingQueue with a capacity of 10. The Consumer takes the items from the queue and consumes them. The BlockingQueue blocks the Producer when the queue is full and blocks the Consumer when the queue is empty.
No comments:
Post a Comment