You are on page 1of 4

PRODUCER-CONSUMER

Name:Riya Mate
Gr no:1710954
____________________________________________________________________________

Consumer.java:

____________________________________________________________
package psuo_thread;
import java.util.*;
import java.util.concurrent.*;
public class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
private String threadId;

public Consumer(BlockingQueue<Integer> queue) {


this.queue = queue;
}

public void run() {


threadId = "Consumer-" + Thread.currentThread().getId();
try {

while (true) {
/*the poll method () takes a specified unit of time
as parameter and waits for specified period of time after which the lock is
released*/
Integer number = queue.poll(10, TimeUnit.SECONDS);

if (number == null || number == -1) {


break;
}

consume(number);

Thread.sleep(1000);
}

System.out.println(threadId + " STOPPED.");


} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
private void consume(Integer number) {

System.out.println(threadId + ": Consumed by consummer " + number);

______________________________________________________________

Producer.java:

package psuo_thread;
import java.util.*;
import java.util.concurrent.*;
public class Producer implements Runnable {
private BlockingQueue<Integer> queue;

// a constructor for initializing the queue

public Producer (BlockingQueue<Integer> queue) {


this.queue = queue;
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
queue.put(produce());

Thread.sleep(500);
}

queue.put(-1); // producing stopped

System.out.println("Producer stopped.");

} catch (InterruptedException ie) {


ie.printStackTrace();
}
}
private int produce() {

//generating a random number


int number = ((int) (Math.random() * 100));
System.out.println("Produced- " + number);

return number;
}

____________________________________________________________________

ProducerConsumerTest.java:

package psuo_thread;
import java.util.*;
import java.util.concurrent.*;

public class ProducerConsumerTest {


public static void main(String[] args) {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(20);

//one producer thread


Thread producer = new Thread(new Producer(queue));
//2 consumer threads
Thread consumer1 = new Thread(new Consumer(queue));
Thread consumer2 = new Thread(new Consumer(queue));

producer.start();

consumer1.start();
consumer2.start();

}
}

You might also like