Calling join function of a thread causes the caller thread (Main thread in this case) to wait for the called thread (t1) to complete. In other words, t1.join() will pause Main thread till t1 completes.
isAlive() is a method in thread to check whether t1 (called thread) is running or not. So, from Main, if you call it after t1.join(), it should always return false (because join wait till t1 dies). Calling t1.isAlive should NOT throw an error unless t1 is uninitialized. Try the code below:
Code:
public class ThreadTest {
public static void main(String[] args) throws Exception
{
boolean state;
MyThread t1 = new MyThread();
state = t1.isAlive(); // No error, state=false, because thread not started yet
System.out.println("Before start() T1::isAlive = " + state);
t1.start();
state = t1.isAlive(); // No error, state=true here, but maybe false under some circumstances depending on wether t1 is still has terminated or not
System.out.println("Just after start() T1::isAlive = " + state);
t1.join();
state = t1.isAlive(); // Always false
System.out.println("After join() T1::isAlive = " + state);
}
static class MyThread extends Thread
{
public void run()
{
try{
Thread.sleep(1000);
}
catch(Exception ex)
{
throw new RuntimeException(ex);
}
}
}
}
Bookmarks