private void step() { int q = this.quantum; int used; Process proc; // we MUST process the queues in reverse order for two reasons // - so a process can't get promoted and re-calculated in another queue // - so our wait times don't get messed up for (int i = level.size() - 1; i >= 0; i--) { // retrieve first item (does not remove!) proc = level.get(i).peek(); // no process? good bye if (proc == null) { continue; } // how much of the quantum do we need to use? used = q < proc.getBurstTime() ? q : proc.getBurstTime(); proc.changeBurstTime(-1 * used); // finished and in the last fifo queue... if (i == level.size() - 1) { // and we're finished, lets remove this process if (proc.getBurstTime() == 0) { level.get(level.size() - 1).poll(); } } // if we aren't finished and are not in the last queue // remove from current queue and move to next queue else { level.get(i).poll(); level.get(i + 1).offer(proc); } // finally, we add all the wait times to the other processes // synchronized(level.get(i)) { for (Process p : level.get(i)) { if (p != proc) { p.addWaitTime(used); } } // } } }
public static void main(String[] args) { final String PROCESSES_FILE = "processes.txt"; final int TIME_QUANTUM = 2; // Read processes in from the file and add them to the ready queue. Queue<Process> readyQueue = new LinkedList<Process>(); for (int i = 0; i < 20; i++) { readyQueue.add(new Process(i, i + 20, i + 13, 0.3)); } int ticker = 0; CPU cpu = new CPU(); Process process = readyQueue.poll(); while (readyQueue.size() > 0) { if (process.getState() == ProcessState.TERMINATED) { readyQueue.remove(process); process = readyQueue.poll(); } else if (process.getBurstTime() % TIME_QUANTUM == 0) { // Put the current process in ready state and add it back to // the queue process.setState(ProcessState.READY); readyQueue.add(process); process = readyQueue.poll(); } process.setState(ProcessState.RUNNING); try { cpu.setPC(process.generateInstruction()); cpu.setRegisters(process.generateRegisters()); process.incrementBurstTime(); System.out.print("CPU at " + ticker + ": " + cpu + " on pid: " + process.getPid() + "\n"); } catch (Exception e) { System.out.println(e.getMessage()); } ticker++; } }