import util.comm.*; /** * Our computation class. */ public class Computer implements Runnable { public final static int ADD = 1; public final static int SUB = 2; public final static int MUL = 3; public final static int DIV = 4; private int op; private Thread tid; DataChannel aChannel; DataChannel bChannel; DataChannel outChannel; public static Computer create(String inA, String inB, String out, int doOp) { if ((doOp < 1) || (doOp > 4)) return null; Computer result = new Computer(); result.tid = new Thread(result); result.tid.setName("Computer ("+out+")"); result.outChannel = DataChannel.getChannel(out); result.aChannel = DataChannel.getChannel(inA, result.tid, 4); result.bChannel = DataChannel.getChannel(inB, result.tid, 4); result.op = doOp; return result; } public void start() { tid.start(); } public void stop() { op = 0; Integer i = new Integer(0); /** make sure our thread wakes up. */ aChannel.releaseChannel(tid); bChannel.releaseChannel(tid); } public void run() { int a, b; while (true) { try { a = ((Integer) aChannel.getValue()).intValue(); b = ((Integer) bChannel.getValue()).intValue(); } catch (DataChannelOverrun e) { System.out.println("OVERRUN on "+tid); break; } catch (DataChannelShutdown x) { System.out.println("Shutting down "+tid.getName()); return; } catch (DataChannelTimeout y) { System.out.println("Timed out "+tid.getName()); return; } catch (Throwable tt) { return; } System.out.print(tid.getName()+" : "); switch (op) { case 0: System.out.println(" exiting."); return; case ADD: System.out.println("ADD "+a+" + "+b+" -> "+(a+b)); outChannel.putValue(new Integer(a+b)); break; case SUB: System.out.println("SUB "+a+" - "+b+" -> "+(a-b)); outChannel.putValue(new Integer(a-b)); break; case MUL: System.out.println("MUL "+a+" * "+b+" -> "+(a*b)); outChannel.putValue(new Integer(a * b)); break; case DIV: System.out.println("DIV "+a+" / "+b+" -> "+(a/b)); if (b == 0) { outChannel.putValue(new Integer(Integer.MAX_VALUE)); } else { outChannel.putValue(new Integer(a / b)); } break; } } } }