Tuesday, December 10, 2019

How To Bring Together Ii Threads Inwards Java? Thread.Join() Example

You tin bring together 2 threads inwards Java past times using join() method from java.lang.Thread class. Why do y'all bring together threads? because y'all desire 1 thread to expression for roughly other earlier starts processing. It's similar a relay race where the minute runner waits until the root runner comes as well as paw over the flag to him. Remember, dissimilar sleep(), join() is non a static method thus y'all demand an object of java.lang.Thread aeroplane to telephone band this method. Now, who calls as well as who wants as well as which thread dies? for example, if y'all convey 2 threads inwards your programme primary thread as well as T1 which y'all convey created. Now if your primary thread executes this describe of piece of job T1.join() (main thread execute whatever y'all convey written inwards the primary method) thus primary thread volition expression for T1 thread to complete its execution. The immediate consequence of this telephone band would live that primary thread volition halt processing at 1 time as well as volition non start until T1 thread has finished. So, what volition hap if T1 is non nonetheless started as well as at that topographic point is no 1 to start T1 thread? Well,  then y'all convey a deadlock but if it's already finished thus primary thread volition start again, provided it acquire the CPU back.

In this tutorial, y'all volition larn how to brand iii threads execute inwards a social club past times using join() method. You an every bit good depository fiscal establishment tally out Java Threads By Scott Oaks as well as Henry Wong to acquire a practiced starting overview of several fundamentals of threads as well as multi-threading.



Thread.join() Example inwards Java

In this program, I convey tried to explicate how to piece of job join() method past times solving a pop multi-threading interview question, how to execute iii threads inwards a order, such that T1 volition start root as well as finished last. In this example, I convey do a aeroplane called ParallelTask which implements Runnable interface as well as used to do multiple threads.

In the run() method it root impress message that it has started as well as thus simply calls join() method to expression for its predecessor thread to conk earlier starting again, subsequently that it prints finished execution. I convey brand these organization thus that all thread complete their execution inwards social club T3, T2 as well as T1.

AfterI do object of Thread T1, I laid its predecessor every bit T2. Similarly I laid T3 every bit predecessor of T2. Since its non guaranteed that when a thread volition start subsequently calling start() method, y'all may run into that T3 starts earlier T2, fifty-fifty if nosotros convey called T2.start() prior to T3.start(), but past times putting those join() statements, nosotros convey guaranteed their execution. There is no agency that T2 volition complete earlier T3 as well as T1 volition complete earlier T2.

You tin every bit good depository fiscal establishment tally out Core Java Volume 1 - Fundamentals past times Cay S. Horstmann to acquire a practiced starting overview of several fundamentals of threads as well as multi-threading.

 You tin bring together 2 threads inwards Java past times using  How to bring together 2 threads inwards Java? Thread.join() example


Now, permit me explicate y'all execution of this program. Our programme starts past times JVM invoking primary method() as well as the thread which executes primary method is called primary thread. How do y'all I know that? do y'all yell upward those "Exception inwards thread "main" java.lang.ArrayIndexOutOfBoundsException" exceptions? You tin run into that Java prints mention of thread every bit "main".

In our main() method nosotros convey root do iii object of ParallelTask aeroplane which is zilch but Runnable. These chore volition live executed past times iii threads nosotros volition do next. We convey given all thread meaningful mention to sympathise output better, its truly best practise to mention your threads.

Next, I convey laid predecessor for each thread, its zilch but roughly other thread object as well as 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, past times setting right predecessors y'all tin impose ordering. In our example, threads volition start inwards whatever social club but volition do processing such that T3 volition complete first, followed past times T2 as well as in conclusion past times T1.


import java.util.concurrent.TimeUnit;  /**  * Simple Java Program to demonstrate how to execute threads inwards a detail order. You  * tin 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 convey iii threads as well as nosotros demand to run inwards the         // social club T1, T2 as well as T3 i.e. T1 should start first         // as well as T3 should start last.         // You tin 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 expression for thread on which bring together is called.          ParallelTask task1 = new ParallelTask();         ParallelTask task2 = new ParallelTask();         ParallelTask task3 = new ParallelTask();          in conclusion Thread t1 = new Thread(task1, "Thread - 1");         in conclusion Thread t2 = new Thread(task2, "Thread - 2");         in conclusion 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 run into that threads convey started inwards different social club thus the social club 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 run into that threads are finished inwards right order. Thread 3 finished first, Thread 2 minute as well as Thread 1 last, the social club nosotros wanted. This is achieved past times using join() method of java.lang.Thread class. It's real useful method to learn.

Some of import points most bring together method inwards Java :

answer]
  • How to halt a thread inwards Java? [solution]
  • How to interruption a thread inwards Java? [example]
  • What is divergence betwixt a thread as well as a process? [answer]
  • How to piece of job CyclicBarrier aeroplane inwards Java? [example]
  • What is divergence betwixt implements Runnable as well as extends Thread inwards Java? [answer]
  • 10 things y'all should know most Thread inwards Java? [article]
  • Difference betwixt CountDownLatch as well as CyclicBarrier inwards Java? [answer]
  • When to piece of job wait() as well as sleep() method inwards Java? [answer]
  • How to piece of job CountDownLatch inwards Java? [example]
  • Difference betwixt Callable as well as Runnable interface inwards Java? [answer]
  • No comments:

    Post a Comment