ThreadControlExample.java
ThreadControlExample.java
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.");
}
}
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.");
}