0
我想創建一個基本運行在一個FIFO順序任務,並提供三個API定製的運行循環退出:addTask(Task task)
,run()
和exit()
的Java:不能從自定義RunLoop實現
任務界面
public interface Task {
public void perform();
public boolean isDone();
public boolean isStarted();
}
任務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());
}
}
任務0-9可以成功運行,但exit()
調用不會終止運行循環。我想在run()
方法中while循環無限運行,我想知道如何退出while循環。謝謝!