Biblioteca Java - Blame information for rev 8

Subversion Repositories:
Rev:
Rev Author Line No. Line
8 mihai 1 package delayqueue;
2  
3 import java.util.Random;
4 import java.util.concurrent.Delayed;
5 import java.util.concurrent.DelayQueue;
6 import java.util.concurrent.TimeUnit;
7  
8 public class DelayTest {
9   public static long BILLION = 1000000000;
10  
11   static class SecondsDelayed implements Delayed {
12     long trigger;
13     String name;
14  
15     SecondsDelayed(String name, long i) {
16       this.name = name;
17       trigger = System.nanoTime() + (i * BILLION);
18     }
19  
20     /**
21      * Compare 2 delayed objects. Returns 0 if objects are queals 1 if the current object is greater than object received as parameter
22      * and -1 if current object is smaller than parameter object.
23      */
24     public int compareTo(Delayed d) {
25       long i = trigger;
26       long j = ((SecondsDelayed)d).trigger;
27       int returnValue;
28       if (i < j) {
29         returnValue = -1;
30       } else if (i > j) {
31         returnValue = 1;
32       } else {
33         returnValue = 0;
34       }
35       return returnValue;
36     }
37  
38     public boolean equals(Object other) {
39       return ((SecondsDelayed)other).trigger == trigger;
40     }
41  
42     public long getDelay(TimeUnit unit) {
43       long n = trigger - System.nanoTime();
44       return unit.convert(n, TimeUnit.NANOSECONDS);
45     }
46  
47     public long getTriggerTime() {
48       return trigger;
49     }
50  
51     public String getName() {
52       return name;
53     }
54  
55     public String toString() {
56       return name + " / " + String.valueOf(trigger);
57     }
58   }//.end of inner class
59  
60   public static void main(String args[])
61           throws InterruptedException {
62  
63         Random random = new Random();
64     //create the queue
65         DelayQueue<SecondsDelayed> queue =
66           new DelayQueue<SecondsDelayed>();
67  
68     //populate the queue with objects which implements Delayed interface
69     for (int i=0; i < 10; i++) {
70       int delay = random.nextInt(10);
71       System.out.println("Delaying: " +
72             delay + " for loop " + i);
73       queue.add(new SecondsDelayed("loop " + i, delay));
74     }
75  
76     //get the objects from queue. An object can be extracted only after the delay has passed.
77     for (int i=0; i < 10; i++) {
78       SecondsDelayed delay = (SecondsDelayed)(queue.take());
79       String name = delay.getName();
80       long tt = delay.getTriggerTime();
81       System.out.println(name + " / Trigger time: " + tt);
82     }//
83  
84   }
85 }