- If a Thread wants to wait until completing some other Thread then we should go for join() method.
- Example: If a Thread t1 wants to wait until completing t2 then t1 has to call t2.join().
- If t1 executes t2.join() then immediately t1 will be entered into waiting state until t2 completes.
- Once t2 completes then t1 can continue its execution.
- Wedding cards printing thread(t2) has to wait until venue fixing Thread (t1) completion, hence t2 has to call t1.join().
- Wedding cards distribution Thread(t3) has to wait until wedding cards printing thread(t2) completion, hence t3 has to call t2.join().
- public final void join()throws InterruptedException
- public final void join(long ms) throws InterruptedException // wait till the mentioned time in millisecs.
- public final void join(long ms, int ns) throws InterruptedException
Join Life cycle:-
Case :-1 : Example:
class MyThread extends Thread
{
public
void run()
{
for(int
i=0;i<5;i++)
{
Thread.yield();
System.out.println("child
thread");
}
}
}
class ThreadYieldDemo
{
public
static void main(String[] args)
{
MyThread
t=new MyThread(); t.start();
for(int
i=0;i<5;i++)
{
System.out.println("main
thread");
}
}
}
|
- If we are commenting line 1 then both Threads will be executed simultaneously and we can't expect exact execution order.
- If we are not commenting line 1 then main Thread will wait until completing child Thread in this the output is Child Thread 10 times followed by Parent Thread 10 times.
class MyThread extends Thread
{
static Thread mt;
public void run()
{
try
{
mt.join();
}
catch
(InterruptedException e){}
for(int i=0;i<10;i++)
{
System.out.println("Child
Thread");
}
}
}
class ThreadJoinDemo
{
public static void main(String[]
args)throws InterruptedException
{
MyThread
mt=Thread.currentThread();
MyThread t=new
MyThread();
t.start();
for(int i=0;i<10;i++)
{
Thread.sleep(2000);
System.out.println("Main
Thread");
}
}
}
|
Output:-
Main Thread
…
…10 times
Main Thread
Chile Thread
…
… 10 times
Child Thread
Case:-3:
- If main thread calls join() on child thread object and child thread called join() on main thread object then both threads will wait for each other forever and the program will be hanged(like deadlock if a Thread class join() method on the same thread itself then the program will be hanged).
Case:-4: Example:
- If a Thread call join() on the same Thread itself than the program will be stucked (this is something like deadlock). In this case Thread has to wait infinite amount of time.
class ThreadDemo {
public static void main() throws
InterruptedException {
Thread.currentThread().join();
// main thread waiting for
}
}
|
Thanks..!!
No comments:
Post a Comment