1 6 7 package com.thoughtriver.open.vectorvisuals.task; 8 9 import java.util.*; 10 11 import com.thoughtriver.open.vectorvisuals.*; 12 13 24 public class TaskManager implements Runnable { 25 26 27 private final VVDisplay vvDisplay; 28 29 30 private final List<AnimationTask> tasks; 31 32 33 private final List<TaskListener> listeners; 34 35 39 private int cycleLength = 10; 40 41 42 private ExecutionState executionState = ExecutionState.stopped; 43 44 51 public TaskManager(final VVDisplay display) { 52 vvDisplay = display; 53 tasks = Collections.synchronizedList(new LinkedList<AnimationTask>()); 54 listeners = new LinkedList<TaskListener>(); 55 } 56 57 64 public int getCycleLength() { 65 return cycleLength; 66 } 67 68 78 public void setCycleLength(final int cycleLength) { 79 this.cycleLength = cycleLength; 80 } 81 82 89 public void addTask(final AnimationTask task) { 90 91 task.setManager(this); 92 tasks.add(task); 93 94 if (tasks.size() == 1) { 96 new Thread (this, "TaskManager Thread").start(); 97 } 98 99 } 100 101 107 public void addTaskListener(final TaskListener listener) { 108 listeners.add(listener); 109 } 110 111 117 public void removeTaskListener(final TaskListener listener) { 118 listeners.remove(listener); 119 } 120 121 128 public List<TaskListener> getListeners() { 129 return new LinkedList<TaskListener>(listeners); 130 } 131 132 136 public void signalExit() { 137 tasks.clear(); 138 } 139 140 145 public ExecutionState getExecutionState() { 146 return executionState; 147 } 148 149 157 public void run() { 158 159 executionState = ExecutionState.running; 161 162 while (!tasks.isEmpty()) { 163 164 long startTime = System.nanoTime(); 165 166 synchronized (tasks) { 167 168 for (Iterator<AnimationTask> iter = tasks.iterator(); iter.hasNext();) { 169 AnimationTask task = iter.next(); 170 boolean taskStillRunning = task.update(); 171 if (!taskStillRunning) { 172 iter.remove(); 173 174 TaskEvent event = new TaskEvent(task, ExecutionState.stopped); 176 for (TaskListener listener : listeners) { 177 listener.taskStateChanged(event); 178 } 179 } 180 } 181 } 182 183 vvDisplay.getViewPane().repaint(); 185 186 long elapsed = (System.nanoTime() - startTime) / 1000000; 188 long remaining = getCycleLength() - elapsed; 189 if (remaining > 0) { 190 try { 191 Thread.sleep(remaining); 192 } 193 catch (InterruptedException ie) { 194 } 196 } 197 } 198 199 executionState = ExecutionState.stopped; 201 } 202 203 } 204 | Popular Tags |