How do I notify a thread from one object to another in the below program without using synchronized methods in the following producer and consumer problem.
I am using a queue
class for the put
and get
methods and using wait()
and notify()
in the run()
method of Producer
class and Consumer
class.
My goal is to use the wait()
and notify()
methods in the Producer
class and Consumer
class and not use them in the Queue
class.
It is giving an IllegalMonitorStateException
.
Program:
package threads;
class Queue{
int num;
int get(int number)
{
System.out.println("The Consumer "+number+" got "+num);
return num;
}
void put(int n,int number)
{
this.num=n;
System.out.println("The producer "+number+" put "+this.num);
}
}
public class producerandconsumer{
boolean flag=false;
class Producer implements Runnable{
Queue q;
int number;
Producer(Queue q,int number)
{
this.q=q;
this.number = number;
new Thread(this,"Producer").start();
}
public void run()
{
for(int i=0;i<10;i++)
{
while(flag)
try{
wait();
}
catch(InterruptedException e){
System.out.println("InterruptedException caught ");
}
q.put(i,number);
flag=true;
notify();
}
}
}
class Consumer implements Runnable{
Queue q;
int number;
Consumer(Queue q,int number)
{
this.q=q;
this.number=number;
new Thread(this,"Consumer").start();
}
public void run()
{
for(int i=0;i<10;i++)
{
while(!flag)
try{
wait();
}
catch(InterruptedException e){
System.out.println("InterruptedException caught ");
}
flag=false;
notify();
q.get(number);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
producerandconsumer pc= new producerandconsumer();
Queue q=new Queue();
pc.new Producer(q,1);
pc.new Consumer(q,1);
}
}
Output of the Program :It is giving an IllegalMonitorStateException
.
The producer 1 put 0 Exception in thread "Producer"
java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at threads.producerandconsumer$Producer.run(producerandconsumer.java:48)
at java.lang.Thread.run(Unknown Source)
Exception in thread "Consumer" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at threads.producerandconsumer$Consumer.run(producerandconsumer.java:76)
at java.lang.Thread.run(Unknown Source)