package ProducerConsumer;
public class Queue {
int item;
boolean isEmpty=false;
public int put(int item)
{
this.item=item;
return this.item;
}
public int get()
{
return item;
}
}
package ProducerConsumer;
public class Producer extends Thread{
Queue q;
public Producer(Queue q)
{
this.q=q;
}
@Override
public void run() {
synchronized (q) {
for(int i=1;i<=5;i++)
{
if(q.isEmpty==false)
try {
q.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Producer produced = "+q.put(i));
q.isEmpty=false;
q.notify();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
package ProducerConsumer;
public class Consumer extends Thread {
Queue q;
public Consumer(Queue q)
{
this.q=q;
}
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (q) {
for(int i=1;i<=5;i++)
{
if(q.isEmpty==true)
try {
q.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ITEM CONSUMED:"+q.get());
q.isEmpty=true;
q.notify();
}
}
}
}
package ProducerConsumer;
public class MainApp {
public static void main(String[] args)
{
Queue q=new Queue();
Thread t1=new Thread(new Producer(q));
//t1.setPriority(1);
t1.start();
Thread t2=new Thread(new Consumer(q));
t2.start();
}
}
This is my output:
ITEM CONSUMED:0
Producer produced = 1
ITEM CONSUMED:1
Producer produced = 2
ITEM CONSUMED:2
Producer produced = 3
ITEM CONSUMED:3
Producer produced = 4
ITEM CONSUMED:4
Producer produced = 5
Question is: why my consumer thread is running first ? I tried setting the priority for my Producer thread also. Its not working. Also, if there is any other flaw in the code or design flaw in code, please do mention.