自定义线程池实现FIFO

自定义线程池

Android中常用的线程池就上面的四种,其实在Java中还有一种常见的线程池(newSingleThreadScheduledExecutor),其实上面的线程池对于我们开发已经是足够了,不过有时候上面的仍然不能满足我们,这时候我们就需要自定义不同功能的线程池。上面我们也说了线程池功能的不同归根到底还是内部的 BlockingQueue 实现不同,所以,我们要实现我们自己相要的线程池,就必须从BlockingQueue(阻塞队列)的实现上做手脚。
那么我们接下来就用 PriorityBlockingQueue来实现一个FIFO的线程池。

1)创建一个基于PriorityBlockingQueue的线程池

[html]  view plain  copy
  1. ExecutorService priorityThreadPool = new ThreadPoolExecutor(3,3,0L,TimeUnit.SECONDS,new PriorityBlockingQueue());  

2)创建一个实现Runnable接口的类,并向外提供我们实现自定义功能,并实现Comparable接口

[html]  view plain  copy
  1. public abstract class PriorityRunnable implements Runnable, Comparable {  
  2.     private int priority;  
  3.    
  4.     public PriorityRunnable(int priority) {  
  5.         if (priority 0)  
  6.             throw new IllegalArgumentException();  
  7.         this.priority = priority;  
  8.     }  
  9.    
  10.     @Override  
  11.     public int compareTo(PriorityRunnable another) {  
  12.         int my = this.getPriority();  
  13.         int other = another.getPriority();  
  14.         return my 1 : my > other ? -1 : 0;  
  15.     }  
  16.    
  17.     @Override  
  18.     public void run() {  
  19.         doSth();  
  20.     }  
  21.    
  22.     public abstract void doSth();  
  23.    
  24.     public int getPriority() {  
  25.         return priority;  
  26.     }  
  27. }  

3)使用PriorityRunnable提交任务

[html]  view plain  copy
  1. ExecutorService priorityThreadPool = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.SECONDS, new PriorityBlockingQueue());  
  2.         for (int i = 1; i 10; i++) {  
  3.             final int priority = i;  
  4.             priorityThreadPool.execute(new PriorityRunnable(priority) {  
  5.                 @Override  
  6.                 public void doSth() {  
  7.                    //做点事儿
  8.                 }  
  9.             });  
  10.         } 

猜你喜欢

转载自blog.csdn.net/qq_36347817/article/details/80112061