LAB 8 - Multithreading in Java

Goal

Java Threads

Java lets you do several things at once by using threads. If your computer has more than one CPU, it may actually run two or more threads simultaneously. Otherwise, it will switch back and forth among the threads at times that are unpredictable unless you take special precautions to control it. There are two different ways to create threads. We will only use one of them here for this assignment.
				  Thread t = new Thread(myDriver);
				  t.start();    // t start running driver, but we don't wait for it to finish 
				  // ... do something else (perhaps start other threads?)
				  // ... later:
				  t.join();  // wait for t to finish driver
				  
The constructor for the built-in class Thread takes one argument, which is any object that has a method called run. This requirment is specified by requiring that Driver implements the Runnable interface. (More precisely, command must be an instance of a class that implements Runnable).
The way a thread "runs" a command is simply by calling its run() method. In this assignment, you are supposed to run each Driver in a separate thread. Thus you might declare something like this:
				   class Driver implements Runnable {
				     	// number of environment states
						private int N;
						// states array
						private int[] s;
						// reward array
						private int[] r;
						// number of cycle 
						private int Tfin;
						// probability of going right
						private double p;
						// future discounting factor
						private double gamma;
						// V
						private double V;
						// constructor
						Driver(int N, int Tfin, double p, double gamma) {
						...
						}
						// run method: run a single simulation
						public void run() {
							   for (int time =0; time < Tfin; time++){
							   	   left_right = Math.random();
								   			  if (left_right < p){  // go right
								   ...
						}
					}
					
The main program MultiSimulation.java, runs all of the drivers concurrently (each in a separate thread), and waits for them to all finish. In outline, your MultiSimulation may look like this:
					int numberOfThreads = 7;
					double[] p = double[numberOfThreads];
					p[0] = 0;
					...
					Thread t[] = new Thread[numberOfThreads];
					for (int i=0; i < numberOfThreads; i++) {
						t[i] = new Thread(new Driver(...,p[i],...));
						t[i].start();
					}
					// waits for all the threads to finish
					for (int i=0; i < numberOfThreads; i++) {
						t[i].join();
					}