Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java .util.*;
- import java.util.concurrent.Semaphore;
- class QUsingSemaphore{
- private boolean isProduced = false;
- private final Semaphore bsemaphore = new Semaphore(1);
- private static int n;
- public synchronized boolean isProduced(){
- return isProduced;
- }
- public synchronized void setProduced(boolean isProduced){
- this.isProduced = isProduced;
- }
- public void produce(int n, int id){
- try{
- if((!isProduced() || this.n!=10) && n > 0){
- bsemaphore.acquire();
- setN(n);
- System.out.println("Produced : "+1+" Item by P"+id+"\nStock="+n+"\n");
- setProduced(true);
- }
- }
- catch(InterruptedException ie){
- ie.printStackTrace();
- }
- finally{
- bsemaphore.release();
- }
- try{
- Thread.sleep(new Random().nextInt(5)*1000);
- }
- catch(InterruptedException ie){
- ie.printStackTrace();
- }
- }
- public void consume(int id){
- try{
- if(isProduced()){
- bsemaphore.acquire();
- int temp=resetN();
- System.out.println("Consumed : "+1+" Item by C"+id+"\nStock="+temp+"\n");
- if(temp==0)
- setProduced(false);
- }
- }
- catch(InterruptedException ie){
- ie.printStackTrace();
- }
- finally{
- bsemaphore.release();
- }
- try{
- Thread.sleep(new Random().nextInt(5)*1000);
- }
- catch(InterruptedException ie){
- ie.printStackTrace();
- }
- }
- public synchronized int resetN(){
- this.n--;
- return this.n;
- }
- public synchronized int getN(){
- return n;
- }
- public synchronized void setN(int n){
- this.n= n;
- }
- }
- class Consumer implements Runnable{
- private final QUsingSemaphore q;
- int id;
- public Consumer(QUsingSemaphore q, int id){
- this.q=q;
- this.id=id;
- }
- public void run(){
- while(true)
- q.consume(id);
- }
- }
- class Producer implements Runnable{
- private final QUsingSemaphore q;
- int id;
- static int count=0;
- public Producer(QUsingSemaphore q, int id){
- this.q=q;
- this.id=id;
- }
- public void run(){
- while(count++ < 20){
- int j = q.getN();
- q.produce(++j, id);
- System.out.println("Total items produced: "+count+"\n");
- }
- System.out.println("20 items produced. Now exiting.");
- System.exit(0);
- }
- }
- class ProducerConsumerTest{
- public static void main(String args[]){
- //Scanner sc=new Scanner(System.in);
- //System.out.println("enter the no. of producers and consumers one by one");
- int np=2, nc=2, i, j;
- QUsingSemaphore q = new QUsingSemaphore();
- for(i=1; i<=np; i++) new Thread(new Producer(q, i)).start();;
- for (i=1; i<=nc; i++ ) new Thread(new Consumer(q,i)).start();;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement