- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Joining Threads in Java
java.lang.Thread class provides a method join() which serves the following purposes usign its overloaded version.
join() − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates.
join(long millisec) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
join(long millisec, int nanos) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds + nanoseconds passes.
See the below example demonstrating the concept.
Example
class CustomThread implements Runnable { public void run() { System.out.println(Thread.currentThread().getName() + " started."); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " interrupted."); } System.out.println(Thread.currentThread().getName() + " exited."); } } public class Tester { public static void main(String args[]) throws InterruptedException { Thread t1 = new Thread( new CustomThread(), "Thread-1"); t1.start(); //main thread class the join on t1 //and once t1 is finish then only t2 can start t1.join(); Thread t2 = new Thread( new CustomThread(), "Thread-2"); t2.start(); //main thread class the join on t2 //and once t2 is finish then only t3 can start t2.join(); Thread t3 = new Thread( new CustomThread(), "Thread-3"); t3.start(); } }
Output
Thread-1 started. Thread-1 exited. Thread-2 started. Thread-2 exited. Thread-3 started. Thread-3 exited.
- Related Articles
- Killing threads in Java
- Difference Between Daemon Threads and User Threads In Java
- Minimum and Maximum Priority Threads in Java
- Java Program to Run Multiple Threads
- How do threads communicate with each other in Java?
- Threads in C#
- Which method must be implemented by all threads in Java?
- User-level threads and Kernel-level threads
- Synchronizing Threads in Python
- Using Threads in Rust Programming
- Threads vs Processes in Linux
- How to destroy threads in C#?
- Threads and Thread Synchronization in C#
- How to handle Python exception in Threads?
- How to use multiple threads in android?

Advertisements