I am trying to implement standard Producer Consumer problem using java.
I done some code to do it.
Here is the code:
Producer Class:
class Producer implements Runnable
{
public Producer()
{
new Thread(this,"Producer").start();
}
public synchronized void put()
{
while(Q.valueset)
{
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
}
Q.valueset=true;
Q.i++;
System.out.println("Put:"+Q.i);
notify();
}
public void run()
{
while(true)
{
put();
}
}
}
Consumer class:
class Consumer implements Runnable
{
public Consumer()
{
new Thread(this,"Consumer").start();
}
public synchronized void get()
{
while(!Q.valueset)
{
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
}
Q.valueset=false;
notify();
System.out.println("Get:"+Q.i);
}
public void run()
{
while(true)
{
get();
}
}
}
Another class for Static variables:
class Q
{
static boolean valueset=false;
static int i;
}
I am having one more class which only contains main and creates the instance of Producer And Consumer.
Now when i am trying to run this program it gives following output:
Put:1
put:2
Got:1
Got:2
I am having misconception related to Wait() and notify() that how it works and how object enters and out's from the monitor.i wanted to clear that concept.
Here the problem is also arising due to Wait and notify().
I know this is very basic question related to Multithreading but these these will help me to clear my misconception.
And i also wanted to understand what is the problem in my code.
I already gone through the following link: