In this tutorial you will see how to use join method in java thread.
In this tutorial you will see how to use join method in java thread.In this tutorial you will see how to use join method in java thread.
join() method -
join method waits until the thread die. If we are using multiple threads and want to continue to next process only after completion of threads. For this, We will use Thread.join() method. It throws InterruptedException if another thread try to interrupt current thread.
join() - It waits for the thread to die.
join(long millis) - It waits at most millis milliseconds for the thread to die. A timeout of 0 means to wait forever.
join(long millis,int nanos)- It waits at most millis milliseconds added time nanos nanoseconds for your thread to die.
Example : In this tutorial we are using join method of thread.
public class ThreadJoin implements Runnable { Thread thread; String name; ThreadJoin(String threadname) { name = threadname; thread = new Thread(this, name); System.out.println("New thread: " + thread); thread.start(); } @Override public void run() { for (int x = 1; x <= 3; x++) { System.out.println("Thread " + Thread.currentThread().getName()); } } public static void main(String[] args) throws Exception { ThreadJoin j1 = new ThreadJoin("1"); ThreadJoin j2 = new ThreadJoin("2"); ThreadJoin j3 = new ThreadJoin("3"); j1.thread.join(); j2.thread.join(); j3.thread.join(); } }
Output :
New thread: Thread[1,5,main] New thread: Thread[2,5,main] New thread: Thread[3,5,main] Thread 1 Thread 1 Thread 1 Thread 2 Thread 3 Thread 3 Thread 3 Thread 2 Thread 2