Java PriorityBlockingQueue class

Description

Java PriorityBlockingQueue class

import java.util.concurrent.PriorityBlockingQueue;

class Task implements Comparable<Task> {
  private int thread;
  private int priority;

  public Task(int thread, int priority) {
    this.thread = thread;
    this.priority = priority;
  }//from w  ww  .ja  v  a2s.  c  om

  public int getThread() {
    return thread;
  }

  public int getPriority() {
    return priority;
  }

  @Override
  public int compareTo(Task e) {
    if (this.priority > e.getPriority()) {
      return -1;
    } else if (this.priority < e.getPriority()) {
      return 1;
    } else {
      return 0;
    }
  }
}

class Job implements Runnable {

  private int id;

  private PriorityBlockingQueue<Task> queue;

  public Job(int id, PriorityBlockingQueue<Task> queue) {
    this.id = id;
    this.queue = queue;
  }

  @Override
  public void run() {
    for (int i = 0; i < 1000; i++) {
      Task event = new Task(id, i);
      queue.add(event);
    }
  }
}

public class Main {
  public static void main(String[] args) {
    PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
    Thread taskThreads[] = new Thread[5];
    for (int i = 0; i < taskThreads.length; i++) {
      Job task = new Job(i, queue);
      taskThreads[i] = new Thread(task);
    }
    for (int i = 0; i < taskThreads.length; i++) {
      taskThreads[i].start();
    }
    for (int i = 0; i < taskThreads.length; i++) {
      try {
        taskThreads[i].join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("Queue Size: " + queue.size());
    for (int i = 0; i < taskThreads.length * 1000; i++) {
      Task event = queue.poll();
      System.out.println("Thread %s: Priority " + event.getThread() + " " + event.getPriority());
    }
    System.out.println("Queue Size: " + queue.size());
  }
}



PreviousNext

Related