Using blocking thread-safe queue ordered by priority
When you work with data structures, you may typically feel the need to have an ordered queue. Java provides PriorityBlockingQueue
that has this functionality.
All the elements you want to add to PriorityBlockingQueue
have to implement the Comparable
interface; alternatively, you can include Comparator
in the queue's constructor. This interface has a method called compareTo()
that receives an object of the same type. So you have two objects to compare: the one that is executing the method and the one that is received as a parameter. The method must return a number less than zero if the local object is less than the parameter. It should return a number bigger than zero if the local object is greater than the parameter. The number must be zero if both the objects are equal.
PriorityBlockingQueue
uses the compareTo()
method when you insert an element in it to determine the position of the element inserted. Bigger elements will either be the...