Search code examples
javamultithreadingsynchronizationthread-synchronization

Consumer-Producer Problem using multi-threading


I'm pretty new to threads and just trying to get a grip on the basics.I'm trying to implement consumer-producer problem.

Can anybody help me with the code.

import java.util.ArrayList;
import java.util.List;


public class T
{
    public static void main(String[] args) {

        ConsumeProduce consumeproduce = new ConsumeProduce();

        C c=new C();
        P p=new P();

        c.start();
        p.start();

        consumeproduce.printList();

    }

}


class C extends Thread
{

    public void run()
    {
        ConsumeProduce consumeproduce =new ConsumeProduce();

        try 
        {
            consumeproduce.consume();

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


class P extends Thread
{
    public void run()
    {

        ConsumeProduce consumeproduce =new ConsumeProduce();

        try {
            consumeproduce.produce();


        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


class ConsumeProduce
{

    static int i=5;
    public List list =new ArrayList<>(10);


    synchronized void consume() throws InterruptedException
    {
        while(i>0)
        {
        wait();
        list.remove(i);
        System.out.println("removed"+i);
        i--;
        notifyAll();
        }
    }

    synchronized void produce() throws InterruptedException
    {
        while(i<=10)
        {
        wait();
        i++;
        list.add(i, 1);
        System.out.println("added"+i);
        notifyAll();
        }
    }

    void printList()
    {
        for (Object i:list)
        {
            System.out.println(i);
        }
    }

}

I'm unable to figure what is wrong with my code.Any sort of help would be useful.


Solution

  • Object of type ConsumeProduce in class C and in class P is different instances of the same class that does not know nothing about each other. Try pass single instance of ConsumeProduce through P and C constructors.