Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

How to Execute threads in order in Java - Join Example

Sometime we need to execute multiple threads in a particular order e.g. if we have three threads T1, T2 and T3 and we want to execute them in a sequence such that thread 2 starts only when first thread finishes it job and T3 starts after T2, but with multithreading in Java there is no guarantee. Threads are scheduled and allocated CPU by thread scheduler which you cannot control but you can impose such ordering by using Thread.join() method. When you start a thread its not guaranteed that which thread will start first and whether the thread started first will finish first, if your application's logic depends upon a sequence its better to do all those operation on single thread because if all code is confined to one thread it will execute in order they were written provided some JIT optimization.



How to run Threads in an order using join() method in Java

Let's see an example of Thread.join() as shown below to learn how you can execute multiple threads in order. This is quite important if your program is spawning multiple threads to load data from multiple sources but need to load data in a given order. 

Here is one scenario where you can use join method in Java:

How to Execute threads in order in Java - Join Example

You can see that parent thread created a thread and let it run its own code using start() method which starts the thread and calls its run() method. After that it went on and executed more code and then it called the join() method because for next set of processing it need the other thread to complete. 

For example, you are making a dish and then you forget an ingredient then you send your children to buy that ingredient form shop. After that you did some work which you can but for next set of work you need that ingredient, hence you are waiting for your son or daughter to come back with the ingredient you want. 

import java.util.concurrent.TimeUnit;

/**
 * Simple Java Program to show how to execute threads in a particular order. You
 * can enforce ordering or execution sequence using Thread.join() method in
 * Java.
 * 
 * @author Javin Paul
 */
public class ThreadJoinDemo{

    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) {

        // we have three threads and we need to run in the
        // order T1, T2 and T3 i.e. T1 should start first
        // and T3 should start last.
        // You can enforce this ordering using join() method
        // but join method must be called from run() method
        // because the thread which will execute run() method
        // will wait for thread on which join is called.

        ParallelTask task1 = new ParallelTask();
        ParallelTask task2 = new ParallelTask();
        ParallelTask task3 = new ParallelTask();

        final Thread t1 = new Thread(task1, "Thread - 1");
        final Thread t2 = new Thread(task2, "Thread - 2");
        final Thread t3 = new Thread(task3, "Thread - 3");

        task1.setPredecessor(t2);
        task2.setPredecessor(t3);

        // now, let's start all three threads
        t1.start();
        t2.start();
        t3.start();
    }

}

Output
Thread - 3 Started
Thread - 2 Started
Thread - 1 Started
Thread - 3 Finished
Thread - 2 Finished
Thread - 1 Finished


That's all about how to execute threads in an order using join() method in Java. While this may look great but there is a drawback that you cannot leverage the parallelism provided by thread if you use join method.

Related Java multithreading Tutorials from Javarevisited Blog


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.