Biblioteca Java - Rev 29

Subversion Repositories:
Rev:
package exemple.fire.delayqueue;

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

public class DelayTest {
  public static long BILLION = 1000000000;
 
  static class SecondsDelayed implements Delayed {
    long trigger;
    String name;
   
    SecondsDelayed(String name, long i) {
      this.name = name;
      trigger = System.nanoTime() + (i * BILLION);
    }
   
    /**
     * Compare 2 delayed objects. Returns 0 if objects are queals 1 if the current object is greater than object received as parameter
     * and -1 if current object is smaller than parameter object.
     */

    public int compareTo(Delayed d) {
      long i = trigger;
      long j = ((SecondsDelayed)d).trigger;
      int returnValue;
      if (i < j) {
        returnValue = -1;
      } else if (i > j) {
        returnValue = 1;
      } else {
        returnValue = 0;
      }
      return returnValue;
    }
   
    public boolean equals(Object other) {
      return ((SecondsDelayed)other).trigger == trigger;
    }
   
    public long getDelay(TimeUnit unit) {
      long n = trigger - System.nanoTime();
      return unit.convert(n, TimeUnit.NANOSECONDS);
    }
   
    public long getTriggerTime() {
      return trigger;
    }
   
    public String getName() {
      return name;
    }
   
    public String toString() {
      return name + " / " + String.valueOf(trigger);
    }
  }//.end of inner class
 
  public static void main(String args[])
          throws InterruptedException {

        Random random = new Random();
    //create the queue
        DelayQueue<SecondsDelayed> queue =
          new DelayQueue<SecondsDelayed>();
       
    //populate the queue with objects which implements Delayed interface
    for (int i=0; i < 10; i++) {
      int delay = random.nextInt(10);
      System.out.println("Delaying: " +
            delay + " for loop " + i);
      queue.add(new SecondsDelayed("loop " + i, delay));
    }
   
    //get the objects from queue. An object can be extracted only after the delay has passed.
    for (int i=0; i < 10; i++) {
      SecondsDelayed delay = (SecondsDelayed)(queue.take());
      String name = delay.getName();
      long tt = delay.getTriggerTime();
      System.out.println(name + " / Trigger time: " + tt);
    }//
   
  }
}