isAlive( ) and join( ) in Java

By: Ivan Lim Emailed: 1675 times Printed: 2153 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The main thread must be the last thread to finish. Sometimes this is accomplished by calling sleep() within main( ), with a long enough delay to ensure that all child threads terminate prior to the main thread. However, this is hardly a satisfactory solution, and it also raises a larger question: How can one thread know when another thread has ended? Fortunately, Thread provides a means by which you can answer this question.

Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread. This method is defined by Thread, and its general form is shown here:

final boolean isAlive( )

The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise. While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join( ), shown here:

final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate. Here is an improved version of the preceding example that uses join( ) to ensure that the main thread is the last to stop. It also demonstrates the isAlive( ) method.

// Using join() to wait for threads to finish.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");}
System.out.println(name + " exiting.");
}
}

class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}

Sample output from this program is shown here:

New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
Two exiting.
Three exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.

As you can see, after the calls to join( ) return, the threads have stopped executing.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(22)


1. View Comment

This Example program is very useful.
good work. Thank You.


View Tutorial          By: sathya at 2008-03-28 02:21:41
2. View Comment

Nice work. Thanks

View Tutorial          By: Karthik at 2009-09-30 08:02:36
3. View Comment

Thanks!! This example was very helpful for me...

View Tutorial          By: Jonathas at 2010-03-11 07:47:51
4. View Comment

Thanks, it was really helpful.
But wouldn't the InterruptedException be caught each time sleep() is used and thus ThreadName Inturrupted would be outputted .


View Tutorial          By: Ron at 2010-06-27 14:22:36
5. View Comment

thanx it was really helpful

View Tutorial          By: Vidisha at 2010-07-09 06:21:32
6. View Comment

its so nice

View Tutorial          By: senthilkumar at 2010-11-11 02:44:37
7. View Comment

Thanks , really appreciate

View Tutorial          By: Marlen at 2010-11-23 10:50:29
8. View Comment

nice intelligent work

View Tutorial          By: santosh at 2010-11-28 01:18:50
9. View Comment

nice example and this is very use ful

View Tutorial          By: jyothi at 2011-02-18 22:24:51
10. View Comment

as we write:
ob1.t.join();
Does t refer to main thread?
or if we write:
ob1.join();
which thread will ob1 wait for end?
if we want it wait for ob2 is ther any usage like:
ob1.ob2.join();
Thanks.


View Tutorial          By: abc123 at 2011-04-03 13:33:33
11. View Comment

Thank you, I need exactly this; cheers :)

View Tutorial          By: Lang at 2011-04-08 09:33:24
12. View Comment

nice work.......

View Tutorial          By: sukirti at 2011-05-06 16:30:19
13. View Comment

nice example 2 uderstand

View Tutorial          By: nilesh doshi at 2011-05-09 01:24:24
14. View Comment

Thank you. It is very good.

View Tutorial          By: tapes pra at 2011-12-08 09:23:31
15. View Comment

Nice example but does not work on me, after executing the three join() statements, the console shows me random execution order instead of the ordered ones the writer gets. How could is be? I'm very looking forward to any reply, thx in advance!

View Tutorial          By: Junjie Zhang at 2012-01-10 03:26:12
16. View Comment

I'm sorry I've misunderstood, join() guarantees that the parent thread won't terminate until it's child threads finish, but not guarantee the execution order of child threads. Thx Ivan for the explanation and example. :)

View Tutorial          By: Junkie Zhang at 2012-01-10 06:02:00
17. View Comment

too difficult example..
no good


View Tutorial          By: giorg at 2012-01-11 22:58:14
18. View Comment

It's a good eg to learn join and isAlive method.But have a doubt
after the join method the isAlive retun false value what is the reason for that?


View Tutorial          By: Nithin at 2012-02-02 08:43:28
19. View Comment

I'd like to Thanks first bcoz your program is really a good and easy to understand...
It helps me for understanding and quickest revision of Thread
THANKS


View Tutorial          By: Pawan at 2012-04-24 19:46:00
20. View Comment

The example given here are simple and easy to run and understand the basics of java.
Thanks
Kranti Kumar


View Tutorial          By: Kranti at 2012-04-26 10:18:34
21. View Comment

please explain thread t=new thread(this,name). What will be the values in this keyword and what System.out.println(t) will print? The output [One,5,main] from where it comes?

View Tutorial          By: Bhavin at 2012-09-28 12:26:55
22. View Comment

New thread: Thread[One,5,main]
How is the second value 5 got?


View Tutorial          By: Venkatesh at 2013-04-21 07:06:15

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ivan Lim
Requesting a Signed Certificate from a Certification Authority example using keytool in Java
The if-then Statement in Java
SELECT Statements
The BodyTag Interface in JSP
Handling Duplicate Form Submissions in Struts
Standard Input and Output in C
A sample that shows Java Beans, Servlets and JSP working together
Recursion in C
Using Multibox in Struts
switch in C
Word Counting sample program in C
Java Bean Scopes in JSF
Using cout.width() in C++
Types of configurations in J2ME
How to get the CLDC and MIDP version from a J2ME program

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
XML and Java - Parsing XML using Java Tutorial
Method Overloading (function overloading) in Java
The Basic Structure of a Simple Java program
Read from a COM port using Java program
Using StringTokenizer in Java
append() in Java
Stack example in Java - push(), pop(), empty(), search()
Vector example in Java
Calendar - sample program in Java
Method Overriding in Java
FileReader and FileWriter example program in Java
Integer: byte, short, int, and long data types in Java
How to use ArrayList in Java
Count number of vowels, consonants and digits in a String in Java
Most Emailed Articles (in Java)
Tomcat and httpd configured in port 8080 and 80
Get user input in Java
FilenameFilter - sample program in Java
Vector in Java - Sample Program
How to use ArrayList in Java
How to Send SMS using Java Program (full code sample included)
Update contents of a file within a jar file
Count number of vowels, consonants and digits in a String in Java
Java program using Method Overriding
What is a deadlock and how to avoid it in Java
how to use boolean data type in Java
Using StringTokenizer in Java
Extract characters in Java
Supports mobile tournament games
MultiLevel Inheritance sample in Java