MultiThreaded Programming  «Prev 

Creating Running Threads - Exercise

Objective: Create a couple of threads and run them concurrently.

Instructions

Create a command-line application named CounterApp that creates two instances of the Counter thread class and then starts each of them.
Pay particular attention to the output of the application when it is executed, as it reveals how the threads are executed concurrently.
Following is the code for a thread class that counts from 1 to 10, printing the numbers as it counts:

class Counter extends Thread {
 static int threadCount = 0;
 int        threadNum;

 public Counter() {
  threadNum = threadCount++;
 }

 public void run() {
  // Count from 1 to 10
  for (int i = 0; i <= 10; i++) {
   System.out.println("Thread " +
   threadNum + " : " + i);
   try {
    sleep((long)(Math.random() * 100.0));
   }
   catch (InterruptedException e) {
   }
  }
 }
}

The Counter class uses an incrementing static member variable, threadCount, as a means of numbering each thread object created from the class. The number of each thread is stored in the threadNum member variable. This number is printed along with the count so that you can tell which thread is doing the counting. Notice that for each iteration of the "for" loop, each thread pauses for a random amount of time between 0 and 100 milliseconds.

Source files

We have supplied the code shown above in a file called CounterApp.txt. You will find this file in the 04-05 folder of the course download available from the Resources page.

Exercise scoring

The full credit for this exercise is 10 points. To receive full credit, you will need to successfully create the source code for the application.

What to submit

In the text box below, cut and paste the source code for the CounterApp application. Click the Submit button to submit the code.