I am trying to create a custom run loop that basically run tasks in a FIFO order and provides three APIs: addTask(Task task)
, run()
and exit()
Task Interface
public interface Task {
public void perform();
public boolean isDone();
public boolean isStarted();
}
Task RunLoop
public class TaskRunLoop {
private Queue<Task> q;
private boolean isRunning;
public TaskRunLoop() {
q = new LinkedList<>();
isRunning = true;
// run();
}
public void addTask(Task t) {
q.offer(t);
}
public void run() {
while(isRunning()) {
while (q.size() > 0) {
Task t = q.poll();
t.perform();
}
}
}
public void exit() {
isRunning = false;
q.removeAll(q);
System.exit(0);
}
public boolean isRunning() {
return isRunning;
}
public static void main(String[] args) {
TaskRunLoop looper = new TaskRunLoop();
for (int i = 0; i < 10; i++) {
looper.addTask(new TaskImpl("task " + i));
}
looper.run();
looper.exit();
System.out.println("still running? " + looper.isRunning());
}
}
The tasks 0 - 9 can be run successfully, but the exit()
call does not kill the run loop. I guess that while-loop in the run()
method runs infinitely, I was wondering how to exit that while loop. Thanks!