I am new to programming and have only done Python in the past. I am working on a university assignment about implementing the Producer-Consumer problem in Java using multithreading concepts. In this case, there are two producers and one consumer. Producer A produces an item at the rate of one every 5 minutes (only an example), producer B produces an item at the rate of one every 6 minutes. The items are placed in a limited size shelf which fits only 5 items.
The consumer takes the item from the shelf every 4 minutes. The consumer will be unable to operate when the shelf is empty and the producers will be unable to operate when the shelf is full.
The program should continue until each producer has produced 10 items and the consumer has consumed 20 items.
This is what I have done so far:
class Buffer{
private int v;
private volatile boolean empty = true;
public synchronized void insert(int x) {
while(!empty) {
try {
wait();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
empty = false;
v = x;
notify();
}
public synchronized int remove() {
while(empty) {
try {
wait();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
empty = true;
return v;
}
}
Above block of code is the class for the shelf mentioned.
The block of code below is the producer class. I have decided to use an array instead of LinkedList since we are not allowed to use SynchronizedList for this assignment.
class Producer extends Thread{
private int size;
private int[] queue;
private int queueSize;
public Producer(int[] queueln, int queueSizeln, String ThreadName) {
super(ThreadName);
this.queue = queueln;
this.queueSize = queueSizeln;
}
public void run() {
while(true) {
synchronized(queue) {
while(size == queueSize) {
System.out.println(Thread.currentThread().getName() + "Shelf is full: waiting...\n");
try {
queue.wait();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
//when queue is empty, produce one, add and notify
int pot = 1;
System.out.println(Thread.currentThread().getName() + " producing...: " + pot);
}
}
}
}
However, I've run into a problem. Since Java wouldn't allow me to append to an array, I have no idea how to continue the code. I initially planned to append the value of pot to:
int[] queue
to visualise the producer producing the item and putting it into the shelf.
I'd really appreciate your help!