I am trying to run task based on length of string in ascending order. However its not working as expected. Here is code I have tried till now:
import java.util.Comparator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class PriorityQueueTest {
public static void main(String... args) throws InterruptedException {
BlockingQueue<Runnable> pq = new PriorityBlockingQueue<Runnable>(5,
new PriorityQueueComparator());
Runner r1 = new Runner("ABC");
Runner r2 = new Runner("AB");
Runner r3 = new Runner("ABCD");
Runner[] arr = new Runner[] { r1, r2, r3 };
ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 3, 0,
TimeUnit.SECONDS, pq);
for (int i = 0; i < arr.length; i++) {
pool.execute(arr[i]);
}
pool.shutdown();
}
}
class PriorityQueueComparator<T extends Runner> implements Comparator<T> {
public int compare(Runner o1, Runner o2) {
if (o1.getName().length() < o2.getName().length()) {
return 1;
}
if (o1.getName().length() > o2.getName().length()) {
return -1;
}
return 0;
}
}
class Runner implements Runnable {
private String name;
public Runner(String sname) {
this.name = sname;
}
public void run() {
System.out.println(name);
}
public String getName() {
return name;
}
}
I expected ouput to be
AB
ABC
ABCD
or
ABCD
ABC
AB
based on compareTo()
method of my customer Comparator
?
I guess custom comparator not getting called.
Please help.