// // CPU Class // // This class implements the CPU, which takes process Queue[0] // and executes it for a quantum // import java.lang.Thread; class CPU extends Thread implements Runnable{ public Queue FIFO; static int quantum = 3; static float overhead = (float) 0.1; static float meanCompletion; float usefulTime; private int count; private boolean keep_running = true, CPU_idle = true; static gui_aux GUI; // Accesor method to GUI public static void setGUI(gui_aux obj) { GUI = obj; } // Constructor for the CPU class. CPU(Queue Q) { FIFO = Q; meanCompletion = 0; usefulTime = 0; count = 0; } // Accesor method to read the quantum public int getQuantum() { return quantum; } // Accesor method to modify the quantum public static void setQuantum(float q) { if (q < 1) q = 1; quantum = (int) q; } // Accesor method to read the context-switch overhead public float getOverhead() { return overhead; } // Accesor method to modify the context-switch overhead public static void setOverhead(float newOverhead) { overhead = newOverhead; } // Accesor method to read the mean completion time public static float getCompletion() { return meanCompletion; } public float execute() { if (!FIFO.isEmpty()) { int time = FIFO.getTime(0); if (!CPU_idle) // There were one process being run, take it out of the CPU if (time > quantum) { FIFO.setTime(0, time - quantum); FIFO.rotate(); } else { // Process completed execution count++; usefulTime += Clock.getTime() - FIFO.getCreation(); meanCompletion = usefulTime/count; FIFO.dequeue(); } if (!FIFO.isEmpty()) { // Give the CPU to the next process CPU_idle = false; time = FIFO.getTime(0); if (time > quantum) { // System.out.println("Running process " + FIFO.getName(0) + " for " + quantum); return quantum + overhead; } else { // System.out.println("Removing process " + FIFO.getName(0)); return time + overhead; } } } // System.out.println("Queue is empty. Cannot execute"); CPU_idle = true; return quantum + overhead; } public void restart() { keep_running = false; quantum = 3; overhead = (float) 0.1; meanCompletion = 0; usefulTime = 0; count = 0; } public void pause() { keep_running = !keep_running; } public void turnoff() { keep_running = false; } public void run() { int sleepTime; while(true) if(keep_running) { try { // System.out.println("Got to CPU.run()"); sleepTime = (int) execute()*1000; GUI.repaint((long)10); // System.out.println("Sleeping for " + sleepTime); Thread.sleep(sleepTime); } catch (InterruptedException e) {} } else // clock paused try { Thread.sleep(2000); } catch (InterruptedException e) {} } }