四 Java多线程-ThreadPool线程池-2( 三 )

最后一个队列是PriorityBlockingQueue , 它是一种有优先级的无界阻塞队列 , 默认的元素执行顺序是升序 , 可以通过自定义接口Comparable<T>实现compareTo()方法来指定队列中的元素执行顺序 。
/** * 测试类 */public class Test1 implements Runnable, Comparable<Test1> {private int priority;public Test1(int priority) {this.priority = priority;}public int getPriority() {return priority;}public void setPriority(int priority) {this.priority = priority;}@Overridepublic int compareTo(Test1 o) {// 返回1时为升序// 返回-1为降序return this.priority > o.priority ? -1 : 1;}@Overridepublic void run() {System.out.println("当前线程 " +Thread.currentThread().getName() +", priority = " +this.priority);}}/** * 有优先级的无界阻塞队列 */public class PriorityBlockingQueueTest {public static void main(String[] args) {ExecutorService service = new ThreadPoolExecutor(1,2,1000,TimeUnit.MILLISECONDS,new PriorityBlockingQueue<>(),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());for (int i = 0; i < 10; i++) {service.execute(new Test1(i));}service.shutdown();}}如果想在线程池的执行线程中加入一点自己希望的动作 , 可以通过自定义ThreadFactory实现 。
/** * 测试类 */public class Test2 implements Runnable {private String name;public Test2(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic void run() {System.out.println(this.getName() + " , 当前线程 " + Thread.currentThread().getName());}}/** * 自定义ThreadFactory */public class SelfDefineThreadPoolExecutor {public static void main(String[] args) {ExecutorService service = new ThreadPoolExecutor(1,2,1000,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(8),// 自定义ThreadFactorynew ThreadFactory() {@Overridepublic Thread newThread(Runnable r) {System.out.println("线程 " + r.hashCode() + " 创建");return new Thread(r, "thread-pool-" + r.hashCode());}},// 加入自定义动作new ThreadPoolExecutor.CallerRunsPolicy()) {public void beforeExecute(Thread thread, Runnable runnable) {System.out.println(((Test2) runnable).getName() + " 准备执行");}public void afterExecute(Thread thread, Runnable runnable) {System.out.println(((Test2) runnable).getName() + " 执行完毕");}public void terminated() {System.out.println("线程池关闭");}};for (int i = 0; i < 10; i++) {service.execute(new Test2("Test2" + i));}service.shutdown();}}其实主要是把常用那几个workQueue搞搞清楚 , 因为这几个在今后的工作中可能会用到 , 尤其是ArrayBlockingQueue , 它和后面会说的另两个神器 , 可以说是是「线程三宝」 。
【四 Java多线程-ThreadPool线程池-2】

经验总结扩展阅读