Executor Service with LIFO ordering

后端 未结 4 760
不知归路
不知归路 2020-12-24 09:43

I wrote a lazy image downloader for my app using an ExecutorService. It gives me great control about how many downloads are running in parallel at what time and so on.

4条回答
  •  旧巷少年郎
    2020-12-24 10:18

    You can do it in two or three simple steps:

    1. Create a LifoBlockingDeque class:

      public class LifoBlockingDeque  extends LinkedBlockingDeque {
      
      @Override
      public boolean offer(E e) { 
          // Override to put objects at the front of the list
          return super.offerFirst(e);
      }
      
      @Override
      public boolean offer(E e,long timeout, TimeUnit unit) throws InterruptedException { 
          // Override to put objects at the front of the list
          return super.offerFirst(e,timeout, unit);
      }
      
      
      @Override
      public boolean add(E e) { 
          // Override to put objects at the front of the list
          return super.offerFirst(e);
      }
      
      @Override
      public void put(E e) throws InterruptedException { 
          //Override to put objects at the front of the list
          super.putFirst(e);
          }
      }
      
    2. Create the executor:

      mThreadPool = new ThreadPoolExecutor(THREAD_POOL_SIZE, 
                                           THREAD_POOL_SIZE, 0L, 
                                           TimeUnit.MILLISECONDS, 
                                           new LifoBlockingDeque());
      
    3. LinkedBlockingDeque is supported only from API Level 9. To use it on earlier versions do the following:

      Use the Java 1.6 implementation - download it from here.

      Then change

      implements BlockingDeque
      

      to

      implements BlockingQueue
      

      To make it compile on Android. BlockingDeque is subtype of BlockingQueue, so no harm done.

    And you're done!

提交回复
热议问题