Question
. ( Buffer class ) You now generalise the above code so that it will involve two or more threads and a common resource which
. (Buffer class) You now generalise the above code so that it will involve two or more threads and a common resource which is a fixed-size buffer. The producer threads produce data into the buffer and the consumer threads consume the data out of the buffer.
Consider the following code fragment, and implement the missing code. You basically need to implement both the Producer and the Consumer class. The following BoundedBuffer class defines an array that will contain the data. The produce() method will be called in Producer class to fill the array with data. The consume() method will be called in Consumer class to remove data from the array. You need to consider the following two synchronisation issues:
- A producer cannot produce a data element to a full buffer
- A consumer cannot consume an element from an empty buffer
code in the /* missing code */
package oosd2;
public class BoundedBuffer { private int[] buffer; private int lastIndex; private boolean isFull; /*creating a buffer with given size */ public BoundedBuffer(int size) { isFull = false; lastIndex = 0; buffer = new int[size]; } public synchronized void produce(int data) { while(isFull==true) { try { wait(); }catch(InterruptedException ex){} } buffer[lastIndex] = data; lastIndex++; if(lastIndex>=buffer.length) { isFull=true; notifyAll(); } } public synchronized int consume() { while(isFull==false) { try { wait(); }catch(InterruptedException ex){} } lastIndex--; if(lastIndex==0) { isFull = false; notifyAll(); } return buffer[lastIndex]; } }
class Producer extends Thread { /* missing code */ }
class Consumer extends Thread { /* missing code */ }
class TestProducerConsumer { public static void main(String args[]) { BoundedBuffer buffer = new BoundedBuffer(5); Producer p1 = new Producer(buffer,1); Producer p2 = new Producer(buffer,2); Consumer c1 = new Consumer(buffer,1); Consumer c2 = new Consumer(buffer,2); p1.start(); p2.start(); c1.start(); c2.start(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started