This discussion is archived
7 Replies Latest reply: Nov 1, 2007 6:23 AM by 807603 RSS

Problem with threading program logic,producer consumer eg.

807603 Newbie
Currently Being Moderated
Hi friends

I wrote 4 classes to implement threading for the basic producer consumer question,ie the producer produces 1 consumer consumes it and so on till 10. One of the output(on running it several times),is unexpected.

these are the 4 lines of the 20 line output,i am unable to understand that how is 1 and 2 both being assigned and retrieved.I made the program for assignment of 1 and retrieval of 1 after it's assignment.Also in one of the outputs consumer retrieves 1 before producer assigns 1.
Can someone help?

Producer assigned 1
producer assigned 2
consumer retrieved 1
consumer retrieved 2
 class HoldInteger
{

private int sharedint;
private boolean empty=false;

HoldInteger()
{
empty=false;
}
  
synchronized public void setSharedInt(int val)
          {
          while(empty==true)
               {
                    try
                         {
                         wait();
                         }
                    catch(InterruptedException e)
                         {
                         System.out.println(e.getMessage());
                         }
               }
                    sharedint=val;
                    empty=true;
                    notifyAll();
          }


      synchronized public int getSharedInt()
     {
          while(empty==false)
          {
               try
               {
                    wait();
               }
               catch(InterruptedException e)
               {
                    System.out.println(e.getMessage());
               }
          }
          empty=false;
          notifyAll();v
          return sharedint;
     }
}
class Producer extends Thread
{
 private HoldInteger phold;

 public Producer (HoldInteger a)
 {
      phold=a;
 }
 public void run()
 {
      for(int i=1;i<=10;i++)
      {
           phold.setSharedInt(i);
           System.out.println("producer assigned"+i);

      }
 }
}
class Consumer extends Thread
{
private HoldInteger chold;

public Consumer(HoldInteger h)
{
     chold=h;
}
public void run()
 {
      int val;
for(int i=0;i<10;i++)
{      
               val=chold.getSharedInt();
      System.out.println("consumer retrieved"+val);
}
}
}
public class SharedCell
{
     public static void main(String args[])
     {
          HoldInteger h=new HoldInteger();
          Producer p=new Producer(h);
          Consumer c=new Consumer(h);
          p.start();
          c.start();

     }
}
Edited by: invincible_me on Nov 1, 2007 9:48 AM

Edited by: invincible_me on Nov 1, 2007 9:54 AM