package Threads_PC_341 ;
public class D_ThreadJoin {
public static Thread thread1 ;
public static Thread thread2 ;
public static void function1 () throws InterruptedException {
//-----------------------Thread 1 is running this function
for ( int i = 0 ; i < 5 ; i ++ ) {
System . out . println ( "Thread " + Thread . currentThread (). getName () + " is running" );
}
}
public static void function2 () throws InterruptedException {
//-----------------------Thread 2 is running this function
thread1 . join (); // Wait for thread1 to finish first
//thread1.join(5000); // Waiting for 5 seconds for thread1 to finish
for ( int i = 0 ; i < 5 ; i ++ ) {
System . out . println ( "Thread " + Thread . currentThread (). getName () + " is running" );
}
}
public static void main ( String [] args ) throws InterruptedException {
/*
join(): is used to start one thread's execution to end of another thread's execution
such that thread B does not start running until thread A ends.
// 1st use: waits for thread A to die.
If any executing thread B calls join() on thread A (i.e; A.join())
Immediately B will enter into waiting state (blocked) until A completes its execution.
// 2nd use: waits at most this much milliseconds for thread A to die
join(long millis) method waits at most this much milliseconds for certain thread to die.
A timeout of 0 means to wait forever
Giving a timeout within join(), will make the join() effect to be nullified after the specific timeout.
*/
thread1 = new Thread (
new Runnable () {
public void run () {
try {
function1 ();
} catch ( InterruptedException e ) {
e . printStackTrace ();
}
}
}
);
thread1 . setName ( "first child" );
thread2 = new Thread (
new Runnable () {
public void run () {
try {
function2 ();
} catch ( InterruptedException e ) {
e . printStackTrace ();
}
}
}
);
thread2 . setName ( "second child" );
thread1 . start ();
thread2 . start ();
}
}