In my application I have 4 threads adding elements to a PriorityBlockingQueue and one thread polling elements out of it. For the polling thread the queue seems to be not accessible. I assume I have to take measures to make it thread safe.
After I take the first element I clear the queue, it should be filled up again by the other 4 filling threads.
The polling and filling threads are inside the same class which holds the PriorityBlockingQueue.
That’s the code for the polling one:
private class UPPainter implements Runnable {
@Override
public void run() {
while(queue.size() > 0) {
ReceivedMsg msg = queue.poll();
queue.clear();
for(final IPacketListener c : listeners) {
new Thread(new ListenerUp(c, msg)).start();
}
}
}
}
When your consumer threads start, the queue is possibly empty, so size = 0 and run() will exit.
You have to actually wait for a msg to be entered.
Also clearing the queue doesn’t seem to make sense to me?
If you want to “close” the consumer threads, send a special end-of-queue message.
Use queue.take() to actually block until an element is inserted: