0% found this document useful (0 votes)
18 views2 pages

Consumer Producer Program

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views2 pages

Consumer Producer Program

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

package batch25;

import [Link];

class ProducerConsumer {
private final int BUFFER_SIZE = 10;
private int[] buffer = new int[BUFFER_SIZE];
private int count = 0;
private int in = 0;
private int out = 0;

public void produce() throws InterruptedException {


Random random = new Random();
while (true) {
synchronized (this) {
while (count == BUFFER_SIZE) {
wait();
}
//[Link](count);
int num = [Link](100); // Generating a random number
[Link]("Producing: " + num);

buffer[in] = num;
in = (in + 1) % BUFFER_SIZE;
count++;
if(count==10)
notify(); // Notify consumer that new data is available
[Link](1000); // To simulate some delay before producing the
next number
}
}
}

public void consume() throws InterruptedException {


while (true) {
synchronized (this) {
while (count == 0) {
wait();
}
//[Link](count);
int consumedNumber = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;

[Link]("Consuming: " + consumedNumber);


if(count==0)
notify(); // Notify producer that space is available in the buffer
[Link](1000); // To simulate some delay before consuming the
next number
}
}
}
}

public class ConsumerProducer {


public static void main(String[] args) throws InterruptedException {
ProducerConsumer producerConsumer = new ProducerConsumer();

Thread producerThread = new Thread(() -> {


try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
});

Thread consumerThread = new Thread(() -> {


try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
});

[Link]();
//[Link]();
[Link]();
}
}

You might also like