I have created my own queue .
Queue.java
public class MyQueue {
private int size;
private Queue<String> q;
public MyQueue(int size ,Queue<String> queue) {
this.size = size;
this.q = queue;
}
//getter and setter
public synchronized void putTail(String s) {
System.out.println(this.size); // It should print 0, 1,2
while (q.size() != size) {
try {
wait();
}
catch (InterruptedException e) {
}
}
Date d = new Date();
q.add(d.toString());
notifyAll();
}
}
MyProducer.java
import com.conpro.MyQueue;
public class MyProducer implements Runnable {
private final MyQueue queue;
private final int size;
MyProducer(int size,MyQueue q) { this.queue = q; this.size = size; }
@Override
public void run()
{
queue.putTail(String.valueOf(Math.random()));
}
}
MyTest.java
public class MyTest {
public static void main(String[] args) {
Queue q = new PriorityQueue<String>();
MyQueue mq = new MyQueue(3,q);
MyProducer p = new MyProducer(3,mq);
MyProducer p1 = new MyProducer(3,mq);
MyProducer p2 = new MyProducer(3,mq);
new Thread(p).start();
new Thread(p1).start();
new Thread(p2).start();
}
}
Now Here I have created 3 producer . So after executing this 3 lines , queue should be full.
Output should be :
0
1
2
But it is only printing 0
.
Why?
P.S : I have written only producer code since I have not reached there yet.