What is join() method?

It a static method of class Thread.It lets one thread "join onto the end"
of another thread. If you have a thread B that can't do its work until another thread
A has completed its work, then you want thread B to "join" thread A. This means that
thread B will not become runnable until A has finished.
Thread t = new Thread();
t.start();
t.join();
The preceding code takes the currently running thread (if this were in the
main() method, then that would be the main thread) and joins it to the end of the
thread referenced by t.
In other words, the
code t.join() means "Join me (the current thread) to the end of t, so that t
must finish before I (the current thread) can run again."
Example:
class demo1 implements Runnable
{
public void run(){
System.out.println("inside demo1");
}
};
class demo
{
public static void main(String[] args){
demo1 obj=new demo1();
Thread t=new Thread(obj,"obj");
t.start();
try{t.join();}catch(Exception e){}
System.out.println("inside main");
}};
Output:
Inside demo1
Inside main
In the above program , join() method is called inside the main thread through thread t. Hence the main thread is going to wait until t expires.
If you remove the join() from the same program then you will get the output in reverse order.
Inside main
Inside demo1

No comments:

Post a Comment