In this exercise, you will become familiar with the concepts of multithreading by writing a multithreaded program.
Using a text editor, create the
- Declare the PrintMe class. This class must implement the Runnable interface.
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){ }
}
}
Using a text editor, create the TestThreeThreads program. In the main method create three threads using the
- Declare the TestThreeThreads class.
public class TestThreeThreads{
//more code here
}
Crate the
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
}
Give each thread a unique name using the setName method.
t1.setName("T1 - Larry");
t2.setName("T2 - Curly");
t3.setName("T3 - Moe");
Start each thread.
t1.start();
t2.start();
t3.start();
On the command line, use the
javac TestThreeThreads.java
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
java TestThreeThreads