Priority is only taken into account if the pool is fully occupied and you are sending several new tasks. If you define your pool with only one thread, you should get the expected result. In your example, all tasks are performed simultaneously, and one ends first, somewhat randomly.
By the way, the related implementation has a problem and throws an exception if your queue is full and you send new tasks.
Below is a working example of what you are trying to achieve (I simplified newTaskFor simplified way, just to make it work - you can improve this part).
It prints: 1 2 3 4 5 .
public class Test { public static void main(String[] args) { PriorityExecutor executorService = (PriorityExecutor) PriorityExecutor.newFixedThreadPool(1); executorService.submit(getRunnable("1"), 1); executorService.submit(getRunnable("3"), 3); executorService.submit(getRunnable("2"), 2); executorService.submit(getRunnable("5"), 5); executorService.submit(getRunnable("4"), 4); executorService.shutdown(); try { executorService.awaitTermination(30, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } } public static Runnable getRunnable(final String id) { return new Runnable() { @Override public void run() { try { Thread.sleep(1000); System.out.println(id); } catch (InterruptedException e) { e.printStackTrace(); } } }; } static class PriorityExecutor extends ThreadPoolExecutor { public PriorityExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); }
assylias May 30 '13 at 11:03 2013-05-30 11:03
source share