So I have a blocking queue implementation. One of the Schedulars is putting a random number to the queue with a delay of 1 seconds, And I have implemented another Schedular with a pool of 10 threads to invoke take() from the message queue.
Important part is the scenario which I am trying to implement is that after taking a single item from the queue the thread waits for 20 seconds (Thread Sleep) and what my understanding was that the other 9 threads in the thread pool would start working parallel while the first thread waits for 20 seconds (Other threads also would wait for 20 seconds) but it's not the case. Other threads of the pool does not seem to start at all. I'm a newb for BlockingQueues and any help would be really appreciated.
My code is as follows.
public class BlockingQueueImpl {
public Queue<Integer> messageQueue = new ConcurrentLinkedDeque();
private void putNumber(Integer number){
try{
System.out.println("putting number to the queue: " + number);
messageQueue.add(number);
System.out.println("size of the queue: " +messageQueue.size());
} catch (Exception e){
e.printStackTrace();
}
}
private void getNumber(){
}
private class RunnableGetImpl implements Runnable {
@Override
public void run() {
try{
Integer num = messageQueue.poll();
System.out.println("Polling from queue, number - "+ num);
if(num!=null){
System.out.println("Sleeping thread for 20 sec"+Thread.activeCount());
Thread.sleep(20000);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
private class RunnablePutImpl implements Runnable {
@Override
public void run() {
Random rand = new Random();
int n = rand.nextInt(100);
n += 1;
putNumber(n);
}
}
public static void main(String[] args){
BlockingQueueImpl blockingQueue = new BlockingQueueImpl();
ScheduledExecutorService executor1 = Executors.newScheduledThreadPool(1);
executor1.scheduleAtFixedRate(blockingQueue.new RunnablePutImpl(), 0, 1000, TimeUnit.MILLISECONDS);
ScheduledExecutorService executor2 = Executors.newScheduledThreadPool(20);
executor2.scheduleAtFixedRate(blockingQueue.new RunnableGetImpl(), 0, 100, TimeUnit.MILLISECONDS);
}
}