import javax.swing.SwingUtilities; /** * This class implements a thread to control running * of a SaM Program and report back when it is done. * This is an easy way of creating a SaM simulator frontend * that needs to run a whole program. */ public class RunThread extends Thread { /** * Provides access to the processor */ protected Processor proc; /** * Provides access to the system */ protected Sys sys; /** * The parent of this thread */ protected ThreadedFrontend parent; /** * The delay after each intruction */ protected int delay = 50; /** * Set when the parent calls stop() in order to stop thread execution at * next cycle */ protected boolean stop = false; /** * Indicates that execution was stopped due to * normal program completion */ public static final int NORMAL = 0; /** * Indicates program was stopped due to an error * in execution */ public static final int ERROR = 1; /** * Indicates that a program was stopped because * it was interrupted by stopExecution() */ public static final int INTERRUPT = 2; /** * Creates a new thread * @param parent the frontend that needs to be updated * @param sys the system to use * @param delay # of milliseconds between command execution */ public RunThread(ThreadedFrontend parent, Sys sys, int delay) { this.parent = parent; this.sys = sys; this.delay = delay; proc = sys.cpu(); } /** * Starts the thread */ public void run() { try { while (proc.get(Processor.HALT) == 0) { if (stop) { syncCompletion(INTERRUPT, null); return; } syncUpdate(); proc.step(); Thread.sleep(delay); } } catch (Exception e) { syncCompletion(ERROR, e); return; } syncCompletion(NORMAL, null); } /** *This is necessary to prevent GUI from updating while handling AWT events * This wraps updateStatus() and runDone() calls, so that they will wait until AWT events complete */ private void syncUpdate() { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { parent.updateStatus(); } }); } catch (Exception e) { } } /** * Called when the thread has completed in order to sync graphics * @param status The exit status code * @param error The error generated, or null if there is none */ private void syncCompletion(final int status, final Exception error) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { parent.runDone(status, error); } }); } catch (Exception e) { } } /** * Stops execution */ public void stopExecution() { stop = true; } }