Java Thread Test4 - Shared Memory


// Ttest4.java
// it contains a test java program, that defines a class jtest with
// a main function that prints howdy, and creates threads from the
// class Thread4.java
// It passes parameters to the threads, a name and an ID number.

// compile this file with the command "javac Ttest4.java"
// your path must include the bin directory of the jdk

// run the program with "java Ttest4"
// on some systems


class Ttest4 {
	public static void main(String argv[]) {
		System.out.println("Howdy from Ttest4");
  		new Thread4("Thread1", 0); //creates a thread
		new Thread4("Thread2", 1); //creates another thread
	}
}


//************* second file *************
// Thread4.java
// It is a thread class to be run from Ttest4
// It receives parameters from the parent, a thread name and ID number
// The thread runs forever (until Ctrl-C at keyboard).
// Illustrates communication through shared-memory (static variables)
// Illustrates how to declare and instantiate an array.

// compile this file with the command "javac Thread4.java"
// your path must include the bin directory of the jdk


public class Thread4 extends Thread {
	private int myid;	// private to this thread
	private int count;      // private count of iterations
	static int sharedarray[] = new int [4]; //static means one copy shared by
						//all the threads - shared memory
						//also shows how to create arrays

	Thread4(String name, int me) { //constructor - executed when thread is created with new
	   super(name); //super is part of the Thread class
	   myid=me;     
	   count = 0;   //initialize count
	   start(); // by default calls method "run"
	}

	public void run() {
	   while (true) {
	        count++;
		sharedarray[0]++;		//all theads access same location
		System.out.println("Howdy from " + Thread.currentThread().getName() + 
		",   id=" + myid + "  count is " + count + "  sharedarry[0]=" +
		sharedarray[0] );
	        try {
                    Thread.sleep(1000);     //milliseconds
                } catch (InterruptedException e) {
                    return;
		}
           }
	}
}