Search Here

Java program for Producer-Consumer Problem


/* Producer-Consumer Problem */

class Factory
{
    int num;
    boolean flag=false;
    synchronized int get()
    {
        if (!flag)
        {
            try
            {
                wait();
            }
            catch (Exception e)
            {
                System.err.println(e);
            }
        }
        System.out.println("\tConsumed: " +num);
        try
        {
            Thread.sleep(1000);
        }
        catch (Exception e)
        {
            System.err.println(e);
        }
        flag=false;
        notify();
        return num;
    }

    synchronized int put(int num)
    {
        if (flag)
        {
            try
            {
                wait();
            }
            catch (Exception e)
            {
                System.err.println(e);
            }
        }
        this.num=num;
        flag=true;
        System.out.println("Produced: " +num);
        try
        {
            Thread.sleep(1000);
        }
        catch (Exception e)
        {
            System.err.println(e);
        }
        notify();
        return num;
    }
}

class Producer implements Runnable
{
    Factory t;
    Producer(Factory t)
    {
        this.t=t;
        new Thread(this,"Producer").start();
    }
    public void run()
    {
        int i = 0;
        for (int x=0; x<10; x++)         
            t.put(i++);
    }
}

class Consumer implements Runnable
{
    Factory t;
    Consumer(Factory t)
    {
        this.t=t;
        new Thread(this,"Consumer").start();
    }
    public void run()
    {
        for (int x=0; x<10; x++)         
            t.get();
    }
}

class  ProducerConsumer
{
    public static void main(String[] args)
    {
        Factory t=new Factory();
        new Producer(t);
        new Consumer(t);
    }
}


JAVA program for Producer-Consumer problem
Output

No comments:

Post a Comment