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();
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."
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");
try{t.join();}catch(Exception e){}
System.out.println("inside main");
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