Producer Consumer using synchonized method


 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
package producerconsumer_using_synchonized_method;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Mahi
 */
public class ProducerConsumer_using_synchonized_method {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Stock sto = new Stock();
        Producer t1 = new Producer(sto, "P1");
        Consumer t2 = new Consumer(sto, "C1");
        Producer t3 = new Producer(sto, "P2");
        
        t1.start();
        t2.start();
        t3.start();
    }
    
}

class Stock{
    private int QOH = 0;

    public synchronized void setQOH(int amount){
        System.out.println("Seting stock started....");
        System.out.println("Adding : "+ amount + " to QOH");
        if(amount > 0){
            QOH = QOH + amount;
            notifyAll();
        }
        System.out.println("Now the new QOH is : "+ QOH);
    }
    
    public synchronized  void getQOH(int amount){
        System.out.println("Get QOH is started...");
        
       
        try{
            while(amount>QOH){
                System.out.println("Now the Consumer is waiting.... "
                        + "Not sufficent stock available");
                wait();
            }
            QOH = QOH-amount;
            System.out.println("Now redusing Stock..." + amount + " from stock");
            
        } catch (InterruptedException ex) {
            Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Now the new stock is : " + QOH);
    }
}

class Producer extends Thread{
    Stock st;
    Random myRand = new Random();
    String tname;
    public Producer(Stock st, String tname) {
        this.st = st;
        this.tname = tname;
    }

    @Override
    public void run() {
        for(int a=0; a<10; a++){
            System.out.println("Producser "+ tname + " On action...");
            st.setQOH(myRand.nextInt(100));
        }
    }
}

class Consumer extends Thread{
    Stock st;
    Random myRand = new Random();
    String tname;

    public Consumer(Stock st, String tname) {
        this.st = st;
        this.tname = tname;
    }

    @Override
    public void run() {
        for(int a=0; a<10; a++){
            System.out.println("Consumer " + tname + " on action....");
            st.getQOH(myRand.nextInt(200));
        }
    }
}


EmoticonEmoticon