| 1 package com.jdon.util.task; 2 3 4 import java.util.LinkedList ; 5 import java.util.Timer ; 6 import java.util.TimerTask ; 7 8 26 public class TaskEngine { 27 28 31 private static LinkedList taskList = null; 32 33 36 private static Thread [] workers = null; 37 38 41 private static Timer taskTimer = null; 42 43 private static Object lock = new Object (); 44 45 static { 46 taskTimer = new Timer (true); 48 workers = new Thread [7]; 50 taskList = new LinkedList (); 51 for (int i=0; i<workers.length; i++) { 52 TaskEngineWorker worker = new TaskEngineWorker(); 53 workers[i] = new Thread (worker); 54 workers[i].setDaemon(true); 55 workers[i].start(); 56 } 57 } 58 59 private TaskEngine() { 60 } 62 63 69 public static void addTask(Runnable r) { 70 addTask(r, Thread.NORM_PRIORITY); 71 } 72 73 87 public static void addTask(Runnable task, int priority) { 88 synchronized(lock) { 89 taskList.addFirst(task); 90 lock.notifyAll(); 93 } 94 } 95 96 106 public static TimerTask scheduleTask(Runnable task, long delay, 107 long period) 108 { 109 TimerTask timerTask = new ScheduledTask(task); 110 taskTimer.scheduleAtFixedRate(timerTask, delay, period); 111 return timerTask; 112 } 113 114 125 public static TimerTask scheduleTask(Runnable task, int priority, 126 long delay, long period) 127 { 128 TimerTask timerTask = new ScheduledTask(task, priority); 129 taskTimer.scheduleAtFixedRate(timerTask, delay, period); 130 return timerTask; 131 } 132 133 139 private static Runnable nextTask() { 140 synchronized(lock) { 141 while (taskList.isEmpty()) { 143 try { 144 lock.wait(); 145 } 146 catch (InterruptedException ie) { } 147 } 148 return (Runnable )taskList.removeLast(); 149 } 150 } 151 152 155 private static class TaskEngineWorker implements Runnable { 156 157 private boolean done = false; 158 159 163 public void run() { 164 while (!done) { 165 nextTask().run(); 166 } 167 } 168 } 169 170 174 private static class ScheduledTask extends TimerTask { 175 176 private Runnable task; 177 private int priority; 178 179 public ScheduledTask(Runnable task) { 180 this(task, Thread.NORM_PRIORITY); 181 } 182 183 public ScheduledTask(Runnable task, int priority) { 184 this.task = task; 185 this.priority = priority; 186 } 187 188 public void run() { 189 addTask(task); 192 } 193 } 194 } 195 | Popular Tags |