0

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!

TonyW
  • 18,375
  • 42
  • 110
  • 183

1 Answers1

2

looper.run(); is not a asynchronous call.
So the execution stays indeed stuck on looper.run(); and never reaches looper.exit();.

To prevent it, you could make your class extends Thread.
Which allows to invoke looper.run(); in a separate thread from the main thread that invokes it.

To start the thread, you should invoke start() and not run() (that is a specific method of Thread) :

public static void main(String[] args) {

    TaskRunLoop looper = new TaskRunLoop();
    for (int i = 0; i < 10; i++) {
        looper.addTask(new TaskImpl("task " + i));
    }

    looper.start(); // instead of run()
    looper.exit();
    System.out.println("still running? " + looper.isRunning());
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215