In the past few days, I have been working on the implementation of priority queues. Because thread safety must be taken into consideration, PriorityQueue is not applicable. A very simple implementation method is to insert the ones with higher priority into one queue, and the ones with lower priority into another queue. When fetching the numbers, first fetch the numbers from the queue with higher priority. The disadvantage of this is that the more priority levels there are, the more queues there are.
Because it needs to be thread-safe, the queue uses ConcurrentLinkedQueue, which is thread-safe, and the API documentation says that ConcurrentLinkedQueue uses an effective "wait-free" algorithm, so its throughput is very good!
The simple code is as follows:
package test;
import java.util.concurrent.ConcurrentLinkedQueue;
public class PriorityQueueTest {
public static void main(String[] args) {
ConcurrentLinkedQueue <String> highPriority = new ConcurrentLinkedQueue <String>(); //High priority
ConcurrentLinkedQueue <String> lowPriority = new ConcurrentLinkedQueue <String>(); //Low priority
highPriority.add( "aaa" );
highPriority.add( "bbb" );
highPriority.add( "111" );
lowPriority.add( "ccc" );
lowPriority.add( "ddd" );
lowPriority.add( "222" );
int i = 0 ,j = 0 , k= 0 ;
while(true){
while(true){
if (!highPriority.isEmpty()){
System.out.print(highPriority.remove());
i++;
k++;
System.out.println( ", i = " +i+ ", k=" +k);
break ;
}
if (!lowPriority.isEmpty()){
System.out.print(lowPriority.remove());
j++;
k++;
System.out.println( ", j = " +j+ ", k=" +k);
break ;
}
break ;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Another way is to implement a very powerful priority queue by inheriting PriorityQueue and implementing the Comparable interface, and then rewriting the compareTo method yourself. However, the disadvantage is that it is not thread-safe!
The code is as follows:
package test;
import java.util.PriorityQueue;
public class PriorityTest extends PriorityQueue<PriorityTest.Test>{
static class Test implements Comparable<Test>{
String packet;
int pride;
public Test(String packet, int pride) {
this .packet = packet;
this .priotity = priotity;
}
public int compareTo(Test arg) {
if (priotity < arg.priotity)
return 1;
else if (priotity > arg.priotity)
return - 1 ;
else
return 0;
}
public String toString(){
return packet;
}
}
public void add(String str, int priority){
super .add( new Test(str,priority));
}
public static void main(String args[]){
PriorityTest pTest = new PriorityTest();
pTest.add( "aaa" , 3 ); //Highest priority
pTest.add( "bbb" , 2 );
pTest.add( "ccc" , 1 );
while (!pTest.isEmpty()){
System.out.println(pTest.remove());
}
}