How do I implement task prioritization using an ExecutorService in Java 5?

前端 未结 6 1927
粉色の甜心
粉色の甜心 2020-11-27 03:51

I am implementing a thread pooling mechanism in which I\'d like to execute tasks of varying priorities. I\'d like to have a nice mechanism whereby I can submit a high prior

6条回答
  •  误落风尘
    2020-11-27 04:05

    I will try to explain this problem with a fully functional code. But before diving into the code I would like to explain about PriorityBlockingQueue

    PriorityBlockingQueue : PriorityBlockingQueue is an implementation of BlockingQueue. It accepts the tasks along with their priority and submits the task with the highest priority for execution first. If any two tasks have same priority, then we need to provide some custom logic to decide which task goes first.

    Now lets get into the code straightaway.

    Driver class : This class creates an executor which accepts tasks and later submits them for execution. Here we create two tasks one with LOW priority and the other with HIGH priority. Here we tell the executor to run a MAX of 1 threads and use the PriorityBlockingQueue.

         public static void main(String[] args) {
    
           /*
           Minimum number of threads that must be running : 0
           Maximium number of threads that can be created : 1
           If a thread is idle, then the minimum time to keep it alive : 1000
           Which queue to use : PriorityBlockingQueue
           */
        PriorityBlockingQueue queue = new PriorityBlockingQueue();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(0,1,
            1000, TimeUnit.MILLISECONDS,queue);
    
    
        MyTask task = new MyTask(Priority.LOW,"Low");
        executor.execute(new MyFutureTask(task));
        task = new MyTask(Priority.HIGH,"High");
        executor.execute(new MyFutureTask(task));
        task = new MyTask(Priority.MEDIUM,"Medium");
        executor.execute(new MyFutureTask(task));
    
    }
    

    MyTask class : MyTask implements Runnable and accepts priority as an argument in the constructor. When this task runs, it prints a message and then puts the thread to sleep for 1 second.

       public class MyTask implements Runnable {
    
      public int getPriority() {
        return priority.getValue();
      }
    
      private Priority priority;
    
      public String getName() {
        return name;
      }
    
      private String name;
    
      public MyTask(Priority priority,String name){
        this.priority = priority;
        this.name = name;
      }
    
      @Override
      public void run() {
        System.out.println("The following Runnable is getting executed "+getName());
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    
    }
    

    MyFutureTask class : Since we are using PriorityBlocingQueue for holding our tasks, our tasks must be wrapped inside FutureTask and our implementation of FutureTask must implement Comparable interface. The Comparable interface compares the priority of 2 different tasks and submits the task with the highest priority for execution.

     public class MyFutureTask extends FutureTask
          implements Comparable {
    
        private  MyTask task = null;
    
        public  MyFutureTask(MyTask task){
          super(task,null);
          this.task = task;
        }
    
        @Override
        public int compareTo(MyFutureTask another) {
          return task.getPriority() - another.task.getPriority();
        }
      }
    

    Priority class : Self explanatory Priority class.

    public enum Priority {
    
      HIGHEST(0),
      HIGH(1),
      MEDIUM(2),
      LOW(3),
      LOWEST(4);
    
      int value;
    
      Priority(int val) {
        this.value = val;
      }
    
      public int getValue(){
        return value;
      }
    
    
    }
    

    Now when we run this example, we get the following output

    The following Runnable is getting executed High
    The following Runnable is getting executed Medium
    The following Runnable is getting executed Low
    

    Even though we submitted the LOW priority first, but HIGH priority task later, but since we are using a PriorityBlockingQueue, any task with a higher priority will execute first.

提交回复
热议问题