Java Multithread Programming Exercise
Problem Statement-1:
Write a Java program to perform a runnable interface, take two threads t1 and t2 and fetch the names of the thread using getName() method.
Expected output:
Thread names are following:
Thread A
Thread B
Solution:
import java.util.*;
public class ExerciseThread implements Runnable {
public static void main(String[] args) {
Thread t1 = new Thread("Thread A");
Thread t2 = new Thread("Thread B");
t1.start(); // Thread started
t2.start(); // Thread started
System.out.println("Thread names are following:");
System.out.println(t1.getName());
System.out.println(t2.getName());
}
public void run() {}
}
/*OUTPUT:
Thread names are following:
Thread A
Thread B */
Explanation:
The class ExerciseThread implements from Runnable class. The Thread t1 and t2 with names "Thread A" and "Thread B" are created and the threads started using start() method. The names of the threads are fetched using the getName() method.