Java Thread Test5 - Concurrency Problem
Notice how the ascending sequence of shared integers is interupted.
// Ttest5.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 Thread5.java
// It passes parameters to the threads, a name and an ID number.
// compile this file with the command "javac Ttest5.java"
// your path must include the bin directory of the jdk
// run the program with "java Ttest5"
// on some systems
class Ttest5 {
public static void main(String argv[]) {
System.out.println("Howdy from Ttest5");
new Thread5("Thread1", 0); //creates a thread
new Thread5("Thread2", 1); //creates another thread
}
}
//************* second file ******************************************
// Thread5.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.
// 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 Thread5 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
Thread5(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++;
temp = sharedarray[0]; //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[0]=" +
sharedarray[0] + " random=" + randwait);
try {
Thread.sleep(randwait); //milliseconds
} catch (InterruptedException e) {
return;
}
sharedarray[0]=temp+1; //introduce concurrency problem
}
}
}