| 8 | import static java.util.concurrent.TimeUnit.*; |
| 9 | |
| 10 | class DelayedTask implements Runnable, Delayed { |
| 11 | private static int counter = 0; |
| 12 | private final int id = counter++; |
| 13 | private final int delta; |
| 14 | private final long trigger; |
| 15 | protected static List<DelayedTask> sequence = |
| 16 | new ArrayList<>(); |
| 17 | DelayedTask(int delayInMilliseconds) { |
| 18 | delta = delayInMilliseconds; |
| 19 | trigger = System.nanoTime() + |
| 20 | NANOSECONDS.convert(delta, MILLISECONDS); |
| 21 | sequence.add(this); |
| 22 | } |
| 23 | @Override public long getDelay(TimeUnit unit) { |
| 24 | return unit.convert( |
| 25 | trigger - System.nanoTime(), NANOSECONDS); |
| 26 | } |
| 27 | @Override public int compareTo(Delayed arg) { |
| 28 | DelayedTask that = (DelayedTask)arg; |
| 29 | if(trigger < that.trigger) return -1; |
| 30 | if(trigger > that.trigger) return 1; |
| 31 | return 0; |
| 32 | } |
| 33 | @Override public void run() { |
| 34 | System.out.print(this + " "); |
| 35 | } |
| 36 | @Override public String toString() { |
| 37 | return |
| 38 | String.format("[%d] Task %d", delta, id); |
| 39 | } |
| 40 | public String summary() { |
| 41 | return String.format("(%d:%d)", id, delta); |
| 42 | } |
| 43 | public static class EndTask extends DelayedTask { |
| 44 | EndTask(int delay) { super(delay); } |
| 45 | @Override public void run() { |
| 46 | sequence.forEach(dt -> |
| 47 | System.out.println(dt.summary())); |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | public class DelayQueueDemo { |
| 53 | public static void |
nothing calls this directly
no outgoing calls
no test coverage detected