1 8 9 package mx4j.timer; 10 11 import java.util.ArrayList ; 12 import java.util.Collections ; 13 14 26 public class TimeQueue 27 { 28 private Thread thread; 29 private volatile boolean running; 30 private final ArrayList tasks; 31 32 35 public TimeQueue() 36 { 37 tasks = new ArrayList (); 38 } 39 40 45 public void start() 46 { 47 synchronized (this) 48 { 49 if (!running) 50 { 51 running = true; 52 thread = new Thread (new Loop(), "MBean Timer Notification Thread"); 53 thread.setDaemon(true); 54 thread.start(); 55 } 56 } 57 } 58 59 66 public void stop() 67 { 68 synchronized (this) 69 { 70 if (running) 71 { 72 running = false; 73 thread.interrupt(); 74 } 75 } 76 } 77 78 81 public int size() 82 { 83 synchronized (this) 84 { 85 return tasks.size(); 86 } 87 } 88 89 93 public void schedule(TimeTask task) 94 { 95 synchronized (this) 96 { 97 tasks.add(task); 98 Collections.sort(tasks); 100 notifyAll(); 101 } 102 } 103 104 108 public void unschedule(TimeTask task) 109 { 110 synchronized (this) 111 { 112 tasks.remove(task); 113 } 114 } 115 116 119 public void clear() 120 { 121 synchronized (this) 122 { 123 tasks.clear(); 124 } 125 } 126 127 private TimeTask getTask() throws InterruptedException 128 { 129 synchronized (this) 130 { 131 while (tasks.isEmpty()) 132 { 133 wait(); 134 } 135 136 TimeTask task = (TimeTask)tasks.get(0); 138 return task; 139 } 140 } 141 142 private class Loop implements Runnable 143 { 144 public void run() 145 { 146 while (running && !thread.isInterrupted()) 147 { 148 try 149 { 150 TimeTask task = getTask(); 151 long now = System.currentTimeMillis(); 152 long executionTime = task.getNextExecutionTime(); 153 long timeToWait = executionTime - now; 154 boolean runTask = timeToWait <= 0; 155 if (!runTask) 156 { 157 Object lock = TimeQueue.this; 159 synchronized (lock) 160 { 161 lock.wait(timeToWait); 163 } 164 } 165 else 166 { 167 unschedule(task); 169 170 if (task.isPeriodic()) 171 { 172 if (task.getFixedRate()) 175 { 176 task.setNextExecutionTime(executionTime + task.getPeriod()); 177 } 178 else 179 { 180 task.setNextExecutionTime(now + task.getPeriod()); 181 } 182 183 schedule(task); 185 } 186 else 187 { 188 task.setFinished(true); 190 } 191 192 try 193 { 194 task.run(); 196 } 197 catch (Throwable x) 198 { 199 x.printStackTrace(); 201 } 202 } 203 } 204 catch (InterruptedException x) 205 { 206 Thread.currentThread().interrupt(); 207 break; 208 } 209 } 210 } 211 } 212 } 213 | Popular Tags |