// Written by Plamen Parvanov package ooos; class Dispatcher extends Thread { private volatile Proc oldT, newT; Dispatcher(){ super("Dispatcher"); setPriority(Thread.MAX_PRIORITY); synchronized(this){ start(); // making sure no proc switches before the Dispatcher Thread is ready try{wait();} catch(InterruptedException ie){ System.err.println("===========================\nErr: "+ie); System.err.flush(); } } } public void run(){ try{ synchronized(this){ notify(); // awake the main thread while(true){ // wait for next context switch try{wait();} catch(InterruptedException ie){ System.err.println("===========================\nErr: "+ie); System.err.flush(); } // make sure the old proc is blocked synchronized(oldT){ //if(oldT.getState()==PCB.DEAD) oldT.stop();// it can't run anyway // awake the new proc if(newT.isAlive()) synchronized(newT) {newT.notify();} else newT.start(); } } } } catch(RuntimeException re){ System.err.println("===========================\nErr: "+re); System.err.flush(); } catch(Exception e){ System.err.println("===========================\nErr: "+e); System.err.flush(); } } protected void ctxsw(Proc oldProc, Proc currProc){ currProc.setState(PCB.CURRENT); if(oldProc!=currProc){ synchronized(oldProc) { synchronized(this){ oldT=oldProc; newT=currProc; notify(); // awake the Dispatcher Thread for new context switch } try{oldProc.wait();} catch(InterruptedException ie){ // block itself System.err.println("===========================\nErr: "+ie); System.err.flush(); } } } } }