Exercise : Using Multithreaded Programming ( Level 1 )

In this exercise, you will become familiar with the concepts of multithreading by writing a multithreaded program.

The purpose of this lab is to create three threads and run them at the same time. While they are running, they will print out their names to the standart output stream. By observing what is printed, you can observe how the threads run and in what order.

 

Preparation 

Before you begin, make sure that you have changed directories to exercises/mod13_threads/exercise1/ using the  cd command in the terminal window.

cd ~/exercises/mod13_threads/exercise1/

 

 

Task 1 - Creating the PrintMe Class

Using a text editor, create the PrintMe class that implements the Runnable interface. Create the run method to perform teh following actions 10 times. Print the name of the current thread and then sleep for 2 seconds.

 

 

Task 2 - Creating the TestThreeThreads Program

Using a text editor,  create the TestThreeThreads program. In the main method create three threads using the PrintMe runnable class. Give each thread a unique name using the setName  method. Start each thread.

 

 

Task 3 - Compiling the TestThreeThreads Program

On the command line, use the javac command to compile the test program.

 

 

Task 4 - Running the TestThreeThreads Program

On the command line, use the java command to run the test program. You should see output similar to this.

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

        T1    -    Larry

        T3    -    Moe

        T2    -    Curry

Run this program several times. Notice that you you may see different results of each execution.

 

Discussion - Can you explain the behavior of your program?