In this lesson, you will learn.
The isAlive() and join() methods are defined in the Thread class.
1. isAlive(): This method returns true if the thread upon which it is called is still running. It returns false if the thread has finished running or has not yet started.
2. join(): This method causes the calling thread (e.g., the main thread) to wait until the thread on which join() is called finishes its execution.
If the thread has already finished, join() return immediately.
package isaliveandjoin;
class MyThread extends Thread {
public void run() {
System.out.println("Thread started: "
+Thread.currentThread().getName());
try {
// Simulating work by sleeping for 2 seconds
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted: "
+Thread.currentThread().getName());
}
System.out.println("Thread finished: "
+Thread.currentThread().getName());
}
}
public class ThreadMethodExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Start the thread
// Check if thread is alive
System.out.println("Is thread alive? " + thread.isAlive());
try {
// Main thread waits for 'thread' to finish
thread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted while
waiting for completion.");
}
// Check again if thread is alive after join
System.out.println("Is thread alive after join? " + thread.isAlive());
System.out.println("Main Thread Exiting......");
}
}
Thread started: Thread-0
Is thread alive? true
Thread finished: Thread-0
Is thread alive after join? false
Main Thread Exiting......
Thread. In its run() method, it simulates some work by sleeping for 2 seconds.MyThread is created and started. The isAlive() method is called to check if the thread is running.join() method is called on the thread instance which makes the main thread wait until MyThread finishes its execution.join() call, isAlive() is checked again to confirm that the thread has stopped running.This example shows how to manage thread execution using isAlive() to check the thread’s status and join() to synchronize threads by making one thread wait for another to finish.
As you can see, after the calls to join( ) return, the threads have stopped executing.
great teaching
You must be logged in to submit a review.