日期:2014-05-20 浏览次数:20636 次
package com.ticmy.concurrency; import java.util.Date; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestPriorityTask { private static PriorityBlockingQueue<Runnable> workQueue = new PriorityBlockingQueue<Runnable>(); private static ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, workQueue); public static void main(String[] args) throws Exception { for(int i=0; i<20; i++) { pool.execute(new Task(i)); } pool.awaitTermination(0, TimeUnit.MILLISECONDS); pool.shutdown(); } } class Task implements Runnable,Comparable<Task> { private int priority;//数值越大,优先级越大 public Task(int priority) { this.priority = priority; } public void run() { System.out.println("当前任务优先级:" + priority + ",执行线程:" + Thread.currentThread() + ",执行此句的时间:" + new Date()); try { TimeUnit.SECONDS.sleep(3); } catch (Exception e){} } public int compareTo(Task o) { return o.priority - priority; } }