Java: simulating round-robin CPU scheduling

Round-robin scheduling gives each ready process a fixed time slice called the quantum. A process that has not finished is moved to the back of the ready queue, so no job can hold the CPU for long and every job keeps getting turns.

Java
import java.util.*;

class Main {
  public static void main(String[] args) {
    String[] names = {"A", "B", "C"};
    int[] remaining = {5, 3, 4};
    int quantum = 2;
    Deque<Integer> ready = new ArrayDeque<>(List.of(0, 1, 2));
    int clock = 0;
    while (!ready.isEmpty()) {
      int p = ready.pollFirst();
      int run = Math.min(quantum, remaining[p]);
      clock += run;
      remaining[p] -= run;
      System.out.println("t=" + clock + " ran " + names[p] + " for " + run);
      if (remaining[p] > 0) {
        ready.addLast(p);
      } else {
        System.out.println(names[p] + " finished at " + clock);
      }
    }
  }
}
Read the full lesson