How to bring together 2 threads inward Java? Thread.join() example

You tin order the sack bring together 2 threads inwards Java yesteryear using join() method from java.lang.Thread class. Why do y'all bring together threads? because y'all desire i thread to aspect for unopen to other earlier starts processing. It's similar a relay race where the minute runner waits until the origin runner comes together with mitt over the flag to him. Remember, different sleep(), join() is non a static method thence y'all demand an object of java.lang.Thread flat to telephone yell upwards this method. Now, who calls together with who wants together with which thread dies? for example, if y'all bring 2 threads inwards your plan master copy thread together with T1 which y'all bring created. Now if your master copy thread executes this business T1.join() (main thread execute whatever y'all bring written inwards the master copy method) together with thence master copy thread volition aspect for T1 thread to complete its execution. The immediate termination of this telephone yell upwards would live that master copy thread volition halt processing at i time together with volition non start until T1 thread has finished. So, what volition hap if T1 is non nevertheless started together with in that place is no i to start T1 thread? Well,  then y'all bring a deadlock but if it's already finished together with thence master copy thread volition start again, provided it acquire the CPU back.

In this tutorial, y'all volition acquire how to brand iii threads execute inwards a companionship yesteryear using join() method. You an besides banking concern tally out Java Threads By Scott Oaks together with Henry Wong to acquire a skillful starting overview of several fundamentals of threads together with multi-threading.




Thread.join() Example inwards Java

In this program, I bring tried to explicate how to role join() method yesteryear solving a pop multi-threading interview question, how to execute iii threads inwards a order, such that T1 volition start origin together with finished last. In this example, I bring do a flat called ParallelTask which implements Runnable interface together with used to do multiple threads.

In the run() method it origin impress message that it has started together with and thence but calls join() method to aspect for its predecessor thread to expire earlier starting again, later on that it prints finished execution. I bring brand these organization thence that all thread complete their execution inwards companionship T3, T2 together with T1.

AfterI do object of Thread T1, I laid its predecessor equally T2. Similarly I laid T3 equally predecessor of T2. Since its non guaranteed that when a thread volition start later on calling start() method, y'all may come across that T3 starts earlier T2, fifty-fifty if nosotros bring called T2.start() prior to T3.start(), but yesteryear putting those join() statements, nosotros bring guaranteed their execution. There is no means that T2 volition complete earlier T3 together with T1 volition complete earlier T2.

You tin order the sack besides banking concern tally out Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to acquire a skillful starting overview of several fundamentals of threads together with multi-threading.

 You tin order the sack bring together 2 threads inwards Java yesteryear using  How to bring together 2 threads inwards Java? Thread.join() example


Now, allow me explicate y'all execution of this program. Our plan starts yesteryear JVM invoking master copy method() together with the thread which executes master copy method is called master copy thread. How do y'all I know that? do y'all recall those "Exception inwards thread "main" java.lang.ArrayIndexOutOfBoundsException" exceptions? You tin order the sack come across that Java prints lift of thread equally "main".

In our main() method nosotros bring origin do iii object of ParallelTask flat which is aught but Runnable. These chore volition live executed yesteryear iii threads nosotros volition do next. We bring given all thread meaningful lift to empathise output better, its truly best practise to lift your threads.

Next, I bring laid predecessor for each thread, its aught but unopen to other thread object together with our ParallelTask has variable predecessor to concur reference of thread to which this thread volition join. This is critical to ensure ordering betwixt multiple thread.

Since each thread calls predecessor.join() method, yesteryear setting right predecessors y'all tin order the sack impose ordering. In our example, threads volition start inwards whatever companionship but volition do processing such that T3 volition complete first, followed yesteryear T2 together with lastly yesteryear T1.


import java.util.concurrent.TimeUnit;  /**  * Simple Java Program to demo how to execute threads inwards a detail order. You  * tin order the sack enforce ordering or execution sequence using Thread.join() method inwards  * Java.  *  * @author Javin Paul  */ public class JoinDemo {      private static class ParallelTask implements Runnable {         private Thread predecessor;          @Override         public void run() {             System.out.println(Thread.currentThread().getName() + " Started");              if (predecessor != null) {                                 try {                     predecessor.join();                                     } catch (InterruptedException e) {                     e.printStackTrace();                 }             }              System.out.println(Thread.currentThread().getName() + " Finished");         }          public void setPredecessor(Thread t) {             this.predecessor = t;         }      }      public static void main(String[] args) {          // nosotros bring iii threads together with nosotros demand to run inwards the         // companionship T1, T2 together with T3 i.e. T1 should start first         // together with T3 should start last.         // You tin order the sack enforce this ordering using join() method         // but bring together method must live called from run() method         // because the thread which volition execute run() method         // volition aspect for thread on which bring together is called.          ParallelTask task1 = new ParallelTask();         ParallelTask task2 = new ParallelTask();         ParallelTask task3 = new ParallelTask();          concluding Thread t1 = new Thread(task1, "Thread - 1");         concluding Thread t2 = new Thread(task2, "Thread - 2");         concluding Thread t3 = new Thread(task3, "Thread - 3");          task2.setPredecessor(t1);         task3.setPredecessor(t2);          // now, let's start all iii threads         t1.start();         t2.start();         t3.start();     }  }  Output 
Thread - 1 Started Thread - 1 Finished Thread - 2 Started Thread - 3 Started Thread - 2 Finished Thread - 3 Finished

From the output, y'all tin order the sack come across that threads bring started inwards different companionship together with thence the companionship their start() method has called, this is fine because y'all don't know which thread volition acquire CPU. It all depends upon mood of thread scheduler, but y'all tin order the sack come across that threads are finished inwards right order. Thread 3 finished first, Thread 2 minute together with Thread 1 last, the companionship nosotros wanted. This is achieved yesteryear using join() method of java.lang.Thread class. It's real useful method to learn.

Some of import points close bring together method inwards Java :

 You tin order the sack bring together 2 threads inwards Java yesteryear using  How to bring together 2 threads inwards Java? Thread.join() example

That's all close how to bring together 2 thread inwards Java using Thread.join() method. You tin order the sack role this to impose ordering betwixt multiple thread e.g. suppose y'all desire to start processing when all your caches are loaded. Though in that place are unopen to concurrency utilities similar CylicBarrier together with CountDownLatch exists, knowing how it industrial plant at bring together flat is real skillful for whatever Java developer. Let me know if y'all bring dubiousness or enquiry close Thread.join() method inwards Java.

Further Learning
Java Fundamentals Part 1,2
Java Concurrency inwards Practice
Applying Concurrency together with Multi-threading to Common Java Patterns

Other Java Multithreading tutorials for curious developers :
  • What is divergence betwixt transient together with volatile variable inwards Java? [answer]
  • How to halt a thread inwards Java? [solution]
  • How to time out a thread inwards Java? [example]
  • What is divergence betwixt a thread together with a process? [answer]
  • How to role CyclicBarrier flat inwards Java? [example]
  • What is divergence betwixt implements Runnable together with extends Thread inwards Java? [answer]
  • 10 things y'all should know close Thread inwards Java? [article]
  • Difference betwixt CountDownLatch together with CyclicBarrier inwards Java? [answer]
  • When to role wait() together with sleep() method inwards Java? [answer]
  • How to role CountDownLatch inwards Java? [example]
  • Difference betwixt Callable together with Runnable interface inwards Java? [answer]

Subscribe to receive free email updates:

0 Response to "How to bring together 2 threads inward Java? Thread.join() example"

Posting Komentar