Java DelayQueue class

Description

Java DelayQueue class


import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

class Task implements Runnable {

  private int id;

  private DelayQueue<Job> queue;

  public Task(int id, DelayQueue<Job> queue) {
    this.id = id;
    this.queue = queue;
  }//  w  ww .j ava2  s  .co m

  @Override
  public void run() {
    Date now = new Date();
    Date delay = new Date();
    delay.setTime(now.getTime() + (id * 1000));

    System.out.printf("Thread %s: %s\n", id, delay);

    for (int i = 0; i < 100; i++) {
      Job event = new Job(delay);
      queue.add(event);
    }
  }
}

class Job implements Delayed {
  private Date startDate;

  public Job(Date startDate) {
    this.startDate = startDate;
  }

  @Override
  public int compareTo(Delayed o) {
    long result = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
    if (result < 0) {
      return -1;
    } else if (result > 0) {
      return 1;
    }
    return 0;
  }

  @Override
  public long getDelay(TimeUnit unit) {
    Date now = new Date();
    long diff = startDate.getTime() - now.getTime();
    return unit.convert(diff, TimeUnit.MILLISECONDS);
  }

}

public class Main {
  public static void main(String[] args) throws Exception {
    DelayQueue<Job> queue = new DelayQueue<>();
    Thread threads[] = new Thread[5];
    for (int i = 0; i < threads.length; i++) {
      Task task = new Task(i + 1, queue);
      threads[i] = new Thread(task);
    }
    for (int i = 0; i < threads.length; i++) {
      threads[i].start();
    }
    for (int i = 0; i < threads.length; i++) {
      threads[i].join();
    }
    do {
      int counter = 0;
      Job event;
      do {
        event = queue.poll();
        if (event != null)
          counter++;
      } while (event != null);
      System.out.printf("At %s you have read %d events\n", new Date(), counter);
      TimeUnit.MILLISECONDS.sleep(500);
    } while (queue.size() > 0);
  }
}



PreviousNext

Related