class MyThread extends Thread {
private String threadName;
MyThread(String name) {
this.threadName = name;
}
// The run method contains the code that constitutes a new thread.
public void run() {
System.out.println(threadName + " is starting.");
try {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " is running, count: " + i);
Thread.sleep(1000); // Sleep for 1 second.
}
} catch (InterruptedException e) {
System.out.println(threadName + " was interrupted.");
}
System.out.println(threadName + " has finished.");
}
}
public class ThreadControlExample {
public static void main(String[] args) {
// Creating threads
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
MyThread t3 = new MyThread("Thread-3");
// Start the threads
t1.start();
t2.start();
t3.start();
try {
// Use join() to wait for t1 to finish before starting the next thread
t1.join();
System.out.println("t1 joined, starting t2.");
t2.join();
System.out.println("t2 joined, starting t3.");
t3.join();
System.out.println("t3 joined, all threads finished.");
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
// Check if the threads are alive
System.out.println("Is t1 alive? " + t1.isAlive());
System.out.println("Is t2 alive? " + t2.isAlive());
System.out.println("Is t3 alive? " + t3.isAlive());
System.out.println("Main thread finished.");
}
}