1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | package producerconsumer_usingsemaphore; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Mahi */ public class ProducerConsumer_usingSemaphore { /** * @param args the command line arguments */ public static void main(String[] args) { Stock myStock = new Stock(); Producer pT = new Producer(myStock); Producer pT2 = new Producer(myStock); Consumer cT = new Consumer(myStock); //pT.start(); cT.start(); //pT2.start(); } } class Stock{ public int QOH = 0; static Semaphore producerSem = new Semaphore(1); static Semaphore consumerSem = new Semaphore(0); public void setQOH(int amount){ try { producerSem.acquire(); if(amount > 0){ QOH = QOH+amount; Thread.sleep(50); } producerSem.release(); }catch (InterruptedException ex) { System.out.println("Error on producer thread"); } } public void getQOH(int amount){ try { consumerSem.acquire(); if(amount < QOH){ System.out.println("Redusing form the QOH ..."); QOH = QOH - amount; System.out.println("New QOH is : " + QOH); Thread.sleep(100); } consumerSem.release(); }catch (InterruptedException ex) { System.out.println("Error on the Consumer thread.."); } } } class Producer extends Thread{ Stock st; Random myRand = new Random(); public Producer(Stock st) { this.st = st; } @Override public void run() { for(int a=0; a<10; a++){ System.out.println("Adding items...."); st.setQOH(myRand.nextInt(100)); System.out.println("Current QOH is : " + st.QOH); } } } class Consumer extends Thread{ Stock st; Random myRand = new Random(); public Consumer(Stock st) { this.st = st; } @Override public void run() { for(int a=0; a<10; a++){ System.out.println("Consuming form the QOH.."); st.getQOH(myRand.nextInt(100)); System.out.println("Now the new QOH is : "+ st.QOH); } } } |
EmoticonEmoticon