How it works...

In this example, you implemented a priority queue of Event objects using PriorityBlockingQueue. As mentioned in the introduction, all the elements stored in PriorityBlockingQueue have to implement the Comparable interface or provide a Comparator object to the constructor of the queue. In this case, you used the first approach, so you implemented the compareTo() method in the Event class.

All the events have a priority attribute. The elements that have a higher value of priority will be the first elements in the queue. When you implement the compareTo() method, if the event executing the method has a priority higher than the priority of the event passed as a parameter, it returns -1 as the result. In another case, if the event executing the method has a priority lower than the priority of the event passed as a parameter, it returns 1 as the result. If both objects have the same priority, the compareTo() method returns 0. In this case, the PriorityBlockingQueue class doesn't guarantee the order of the elements.

We implemented the Task class to add the Event objects to the priority queue. Each task object adds 1,000 events to the queue, with priorities between 0 and 999, using the add() method.

The main() method of the Main class creates five Task objects and executes them in the corresponding threads. When all the threads had finished their execution, you wrote all the elements to the console. To get the elements from the queue, we used the poll() method. This method returns and removes the first element from the queue.

The following screenshot shows part of the output of an execution of the program:

You can see how the queue has a size of 5,000 elements and how the first elements have the biggest priority value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.165.2