多线程应用程序Java中的PrioirtyBlockingQueue

时间:2018-07-02 18:33:27

标签: java multithreading

我已经看到“ thedarkpassenger”对如何在多线程应用程序中实现PrioirtyQueue进行了很好的解释,但是下面只有一个可运行的类

如果我们必须实现多个Runnable类怎么办? 如何修改类MyFutureTask和main以容纳多个Runnable类?

Driver类:此类创建一个执行程序,该执行程序接受任务并随后将其提交执行。在这里,我们创建了两个任务,一个任务具有低优先级,另一个任务具有高优先级。在这里,我们告诉执行程序运行最多1个线程,并使用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));
}

MyTask类:MyTask实现Runnable并接受优先级作为构造函数中的参数。运行此任务时,它将打印一条消息,然后使线程进入睡眠状态1秒钟。

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类:由于我们使用PriorityBlocingQueue来保存任务,因此我们的任务必须包装在FutureTask中,并且FutureTask的实现必须实现Comparable接口。 Comparable接口比较2个不同任务的优先级,并以最高优先级提交任务以供执行。

 public class MyFutureTask extends FutureTask<MyFutureTask>
      implements Comparable<MyFutureTask> {

    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();
    }
  }

优先级:自我解释的优先级。

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;
  }


}

现在,当我们运行此示例时,我们将获得以下输出

以下Runnable正在执行高 以下Runnable正在执行低位

0 个答案:

没有答案