Java Thread start and join method example

 When implementing Runnable interface for Thread then below points need to remember:

(1) Implement run() method

(2) run() method should be called with start() method, directly calling run() will not work as thread.

(3) If there is no join() call, then even after executing start(), first the calling method will complete its execution then it will go to run().

(4) If there is join() call after start() then code will directly go to run() and complete run() execution first then come back to calling method for further execution.

(5) join() should be called after start() and catching InterruptedException is mandatory for join().


package com.evaluatethecode;

public class ThreadWithoutJoinExample implements Runnable {

public static void main(String[] args) {

System.out.println("Calling start() is required to execute run()");
Thread etcThread = new Thread(new ThreadJoinExample());
etcThread.start();
System.out.println("This method does not have join method call ");

}

public void run() {
System.out.println("Run method: Evaluate the code");
}
}

Output:
Calling start() is required to execute run()
This method does not have join method call 
Run method: Evaluate the code

package com.evaluatethecode;

public class ThreadJoinExample implements Runnable{

public static void main(String[] args) {

Thread etcThread = new Thread(new ThreadJoinExample());
etcThread.start();
System.out.println("Before join method call");
try {
etcThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("After join method call");

}

public void run() {
System.out.println("Run method: Evaluate the code");
}
}

Output:
Before join method call
Run method: Evaluate the code
After join method call

No comments:

Post a Comment