Exercise : Using Multithreaded Programming ( Level 3 )

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

 

 

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.

  1. Declare the PrintMe class. This class must implement the Runnable interface.
class PrintMe implements Runnable{
     //More code here
}
  1. Crate the run method to loop the following 10 times. Print the name of the current thread and then sleep for 2 seconds.

public void run(){
    for(int x= 0; x<10; x++){
     System.out.println(Thread.currentThread().getName());
        try{
            Thread.sleep(2000);
        }catch(Exception e){  }
    } 
}

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.

  1. Declare the TestThreeThreads class.

public class TestThreeThreads{
        //more code here
}

  1. Crate the main method.

    1. Create three thread objects and pass an instance of the PrintName class each constructor.

public static void main(String [] args){
    Runnable prog = new PrintMe();
    Thread t1 = new Thread(prodg);
    Thread t2 = new Thread(prodg);
    Thread t3 = new Thread(prodg);

    //more code here
}

 

  1. Give each thread a unique name using the setName method.

t1.setName("T1 - Larry");
t2.setName("T2 - Curly");
t3.setName("T3 - Moe");

  1. Start each thread.

t1.start();
t2.start();
t3.start();

 

Task 3 - Compiling the TestThreeThreads Program

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

javac TestThreeThreads.java

 

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 that shown in "Task 4 - Running the TestThreeThreads Program" on page Lab 13 - 3.

java TestThreeThreads