Producer – Consumer problem in Java Multithreading

Hello friends, this is one of the best example of multithreading for solving producer consumer problem. Save the following code with a suitable file name. Compile the saved file and run/execute the program using : java I

*here I is the class where main method is present.


class First{
    int n;
    boolean value=false;
    synchronized int get(){
        if(!value){
            try{
                wait();
            }
            catch(InterruptedException e){
                System.out.println(“Inteerupted Exception”);
            }
        }
        System.out.println(“Got: “+n);
        value=false;
        notify();
        return n;
    }
    synchronized void put(int n){
        if(value){
            try{
                wait();
            }catch(InterruptedException e){
                System.out.println(“Inteerupted Exception”);
            }
        }
        this.n=n;
        value=true;
        System.out.println(“Put: “+n);
        notify();
    }
}
class Producer implements Runnable{
    First f;
    Producer(First f){
        this.f=f;
    }
    public void run(){
        int m=0;
        for(int k=1; k            f.put(++m);
        }
    }
}
class Consumer implements Runnable{
    First f;
    Consumer(First f){
        this.f=f;
    }
    public void run(){
        for(int k=1; k            f.get();
        }
    }
}
class I{
public static void main(String[] args){
    First f=new First();
    Producer p=new Producer(f);
    Consumer c=new Consumer(f);
   
    Thread t1=new Thread(p);
    Thread t2=new Thread(c);
   
    t1.start();

    t2.start();
}
}

enable/disable : t1.start(); and t2.start(); one by one to see the effect and concept behind this example.