Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
A thread in Java is considered to be a thread of execution in a program. Java.lang.thread includes various methods which help in running multiple threads concurrently. One of the commonly used method is the Join Method in Java. Let’s explore this method in the below sequence.
Join method in Java allows one thread to wait until another thread completes its execution. In simpler words, it means it waits for the other thread to die. It has a void type and throws InterruptedException. Joining threads in Java has three functions namely,
Let’s implement all the joins in Java one by one.
Example of join() Method in Java
package Edureka; import java.io.*; import java.util.*; public class Threadjoiningmethod extends Thread{ public void run(){ for(int i=1;i<=4;i++){ try{ Thread.sleep(500); }catch(Exception e){System.out.println(e);} System.out.println(i); } } public static void main(String args[]){ Threadjoiningmethod th1=new Threadjoiningmethod (); Threadjoiningmethod th2=new Threadjoiningmethod (); Threadjoiningmethod th3=new Threadjoiningmethod (); th1.start(); try{ th1.join(); } catch(Exception e){ System.out.println(e); } th2.start(); th3.start(); } }
Output:
1
2
3
4
1
1
2
2
3
3
4
4
Explanation: Here you can notice thread1 first complete its task, then thread2 and thread3 will execute.
Example of join(long millis) Method in Java
package Edureka; import java.io.*; import java.util.*; public class Threadjoiningmethod extends Thread{ public void run(){ for(int i=1;i<=4;i++){ try{ Thread.sleep(200); }catch(Exception e){System.out.println(e);} System.out.println(i); } } public static void main(String args[]){ Threadjoiningmethod th1=new Threadjoiningmethod(); Threadjoiningmethod th2=new Threadjoiningmethod(); Threadjoiningmethod th3=new Threadjoiningmethod(); th1.start(); try{ th1.join(1000); } catch(Exception e){ System.out.println(e); } th2.start(); th3.start(); } }
Output:
1
2
3
4
1
1
2
2
3
3
4
4
Explanation: Here you can notice thread1 completes its task for 200millisecond(4 times as sleep time is 200), then thread2 and thread3 will execute.
If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.
Thus we have come to an end of this article on ‘Join method in Java’. If you wish to learn more, check out the Java Online Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this blog “Join method in Java” and we will get back to you as soon as possible.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 14th December,2024 14th December SAT&SUN (Weekend Batch) | View Details |
edureka.co