1.Write the Producer and Consumer processes by using the shared bounded-buffer a
ID: 3732800 • Letter: 1
Question
1.Write the Producer and Consumer processes by using the shared bounded-buffer as follows:
*Remark: Consider the following assumption:
-Producer produces a message/information that is consumed by a cosumer.
-Bounded-buffer assumes that its buffer size is fixed (e.g. 20).
#define BUFFER_SIZE 20
typedef struct {
. . .
} item;
item buffer [ BUFFER_SIZE];
int in=0; /* the next free position in the buffer */
int out=0; /* the first full position in the buffer */
A. Producer code below:
B.Consumer code below:
Explanation / Answer
a)Producer Class
b)Consumer Class
}
Tester Class
import java.util.Queue; import java.util.Random; public class Producer implements Runnable { private Queue<Integer> sharedQueue; private final int MAX_SIZE = 5; public Producer(Queue<Integer> sharedQueue) { this.sharedQueue = sharedQueue; } public void run() { while (true) { synchronized(sharedQueue) { while (sharedQueue.size() ==5) { try { System.out.println("Producer is waiting to consume object by comsumer.."); sharedQueue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Random random = new Random(); int data = random.nextInt(MAX_SIZE); sharedQueue.add(data); System.out.println("Produced::"+data); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } sharedQueue.notify(); } } } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.