You are on page 1of 2

“Computer Programming 2”

09 Hands-on Activity 1 - ARG


Instructions: A thread can be in one of the following states:

Create two (2) threads named by the user. Display their various states using getState( ).
In the main method:

1. Enable user input.


2. Create two (2) threads.
3. Ask the user to enter a name for each thread.
4. Show the names and states of the threads.
5. Start the threads.
6. Have the threads sleep for half a second.
7. Show the names and states of the threads.

Answer:

Codes:
import java.util.Scanner;

public class MyClass extends Thread {


public static void main(String args[]) {
MyClass thread1 = new MyClass();
MyClass thread2 = new MyClass();

String tn1, tn2;


Scanner s = new Scanner(System.in);

System.out.print("Name your first thread: ");


tn1 = s.nextLine();
System.out.print("Name your second thread: ");
tn2 = s.nextLine();

thread1.setName(tn1);
thread2.setName(tn2);

System.out.println(thread1.getName() + " is " + thread1.getState());


System.out.println(thread2.getName() + " is " + thread2.getState());

System.out.println("\n\nStarting the threads...");


thread1.start();
thread2.start();

try {
thread1.sleep(500);
thread2.sleep(500);

System.out.println("\n\nAfter sleep...");

System.out.println(thread1.getName() + " is " + Thread.State.TERMINATED);


System.out.println(thread2.getName() + " is " + Thread.State.TERMINATED);

} catch(InterruptedException e) {

System.out.println("\n\nAfter thread is running...");

System.out.println(thread1.getName() + " is " + thread1.getState());


System.out.println(thread2.getName() + " is " + thread2.getState());

}
}

public void run () {


System.out.println(Thread.currentThread().getName() + " is " +
Thread.currentThread().getState());

}
Output:

You might also like