/** * A simple implementation using threads of the the one-dimensional finite difference computation * described in "Designing and Building Parallel Programs" by Ian Foster's * (see Section 1.4 - http://www-unix.mcs.anl.gov/dbpp/text/node10.html). * * @author Scott W. Russell * @version 5/2/2008 for CS333 Spring 2008 */ public class OneDimFiniteDiff { /** * Display value contained by each node. */ public static String showNodeData(Node[] nodes) { String result = ""; if (nodes == null) return result; result += "{"; for (int i = 0; i < nodes.length; i++) result += nodes[i].getValue() + ", "; result += "}"; return result; } public static void main(String[] args) throws InterruptedException { int timeSteps = TIME_STEPS; //If command line argument present, gives number of time steps in seconds. if (args.length > 0) { try { timeSteps = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("First argument, number of time steps must be an integer."); System.exit(1); } } // take number of elements and number of steps as args? Node[] nodes = new Node[NUM_NODES]; Thread[] nodeThread = new Thread[NUM_NODES]; int time = 0; // create leftmost node nodes[0] = new Node(Integer.toString(0),values[0],null,null); //create all other nodes and set their left neighbor for (int i = 1; i < NUM_NODES; i++) { nodes[i] = new Node(Integer.toString(i), values[i], nodes[i-1], null); } // set right neighbors of except rightmost node for (int i = 0; i < LAST_NODE; i++) { nodes[i].setNeighbor(RIGHT,nodes[i+1]); } System.out.println("Initial node config at time t = " + time + ": " + showNodeData(nodes)); for (time=0; time < timeSteps; time++) { // create and start thread for each node for (int i = 0; i < NUM_NODES; i++) { nodeThread[i] = new Thread(nodes[i]); nodeThread[i].start(); } // wait for all threads to complete before continuing // is there a better way? Can't join a thread group? for (int i = 0; i < NUM_NODES; i++) { nodeThread[i].join(); } System.out.println("Update from t=" + time + " to t=" + (time+1) + " completed.\nNode config at time t = " + (time+1) + ": " + showNodeData(nodes)); } } // instance variables - replace the example below with your own private static final int NUM_NODES = 8; private static final int LAST_NODE = 7; private static final int NUM_STEPS = 4; private static final int TIME_STEPS = 2; public static final boolean LEFT = true; public static final boolean RIGHT = false; private static double[] values = {1,1,2,3,3,2,1,1}; }