Java Thread Test6 - Concurrency Problem Synchonized

Notice how the ascending sequence of shared integers is now correct.

// Ttest6.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 Thread6.java
// It passes parameters to the threads, a name and an ID number.

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

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


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

//************* second file ******************************************

// Thread6.java
// It is a thread class to be run from Ttest5
// 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.
// Illustrates concurrency problem: race conditions.
// Illustrates how to use random numbers.
// Solves race conditions with synchronize, to protect the critical section

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

import java.lang.Math;
import java.util.Random;
public class Thread6 extends Thread {
	private int myid;	// private to this thread
	private int count;      // private count of iterations
	private int randwait;   // random amount of sleep time
	static int sharedarray[] = new int [4]; //static means one copy shared by
						//all the threads - shared memory
						//also shows how to create arrays
  	Random randGen;		// a pointer to a Random generator
	private int temp;	// holds sharedarray value temporarily

	Thread6(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
	   randGen = new Random(myid);	//instantiate randGen and seed the sequence
	   start(); // by default calls method "run"
	}

	public void run() {
	   while (true) {
	        count++;
		synchronized(sharedarray) {
		   temp = sharedarray[3];		//all theads access same location
		   randwait = (Math.abs(randGen.nextInt()) % 1000) +1;

		   System.out.println("Howdy from " + Thread.currentThread().getName() + 
		   ",   id=" + myid + "  count is " + count + "  sharedarry[3]=" +
		   sharedarray[3] + " random=" + randwait);

	           try {
                       Thread.sleep(randwait);     //milliseconds
                   } catch (InterruptedException e) {
                       return;
		   }
		   sharedarray[3]=temp+1;		//introduce concurrency problem
		}
	   }	
	}
}