-1

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.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
Ankush Dutt
  • 143
  • 8
  • What's not working? Are there errors? – Mark Oct 22 '18 at 12:53
  • 1
    The Consumer create its own ConsumeProduce instance, and the producer too. So they don't share anything. Besides, your code is not correctly indented, which is really somthing you should master before starting using threads. – JB Nizet Oct 22 '18 at 12:56
  • While you haven't stated what your actual problem is, i'm guessing that the core of the initial problem is that you have three separate instances of ConsumeProduce. Presumably, you want one instance which is shared among the threads. – jtahlborn Oct 22 '18 at 12:59

1 Answers1

2

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.

Andrew
  • 36
  • 1