Wednesday, May 1, 2024
HomeJavaFind out how to run Threads in an Order in Java -...

Find out how to run Threads in an Order in Java – Thread.Be part of() Instance


Howdy Java programmers, if you have to execute a number of threads in a selected order, for instance when you’ve got three threads T1, T2 and T3 and we wish to execute them in a sequence such that thread 2 begins solely when first thread finishes it job and T3 begins after T2, however with multithreading in Java there isn’t a assure. Threads are scheduled and allotted CPU by thread scheduler which you can not management however you may impose such ordering through the use of Thread.be part of() technique. If you begin a thread its not assured that which thread will begin first and whether or not the thread began first will end first, in case your utility’s logic relies upon upon a sequence its higher to do all these operation on single thread as a result of if all code is confined to at least one thread it would execute so as they have been written offered some JIT optimization.

Find out how to run Threads in an order utilizing be part of() technique in Java

Let’s have a look at an instance of Thread.be part of() technique as proven under to be taught how one can execute a number of threads so as. That is fairly essential in case your program is spawning a number of threads to load information from a number of sources however must load information in a given order. 

Right here is one situation the place you should utilize be part of technique in Java:

How to Execute threads in order in Java - Join Example

You possibly can see that guardian thread created a thread and let it run its personal code utilizing begin() technique which begins the thread and calls its run() technique. After that it went on and executed extra code after which it referred to as the be part of() technique as a result of for subsequent set of processing it want the opposite thread to finish. 

For instance, you make a dish and then you definately overlook an ingredient then you definately ship your youngsters to purchase that ingredient type store. After that you simply did some work which you’ll be able to however for subsequent set of labor you want that ingredient, therefore you’re ready on your son or daughter to come back again with the ingredient you need. 

import java.util.concurrent.TimeUnit;

/**
 * Easy Java Program to indicate how one can execute threads in a selected order. You
 * can implement ordering or execution sequence utilizing Thread.be part of() technique in
 * Java.
 * 
 * @writer Javin Paul
 */
public class ThreadJoinDemo{

    personal static class ParallelTask implements Runnable {
        personal Thread predecessor;

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " Began");

            if (predecessor != null) {
                
                strive {
                    predecessor.be part of();
                    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName() + " Completed");
        }

        public void setPredecessor(Thread t) {
            this.predecessor = t;
        }

    }

    public static void major(String[] args) {

        // we've three threads and we have to run within the
        // order T1, T2 and T3 i.e. T1 ought to begin first
        // and T3 ought to begin final.
        // You possibly can implement this ordering utilizing be part of() technique
        // however be part of technique should be referred to as from run() technique
        // as a result of the thread which can execute run() technique
        // will watch for thread on which be part of is known as.

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

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

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

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

}

Output
Thread - 3 Began
Thread - 2 Began
Thread - 1 Began
Thread - 3 Completed
Thread - 2 Completed
Thread - 1 Completed

That is all about how one can execute threads in an order utilizing be part of() technique in Java. Whereas this will look nice however there’s a disadvantage that you simply can not leverage the parallelism offered by thread for those who use be part of technique. In case you requested me that whether or not I’ve actually used be part of() in any actual mission or in manufacturing code? 

Effectively, Sure, I’ve used it lengthy again earlier than the CountDownLatch and cyclic barrier was introduce to be sure that my utility begin taking orders solely after it has loaded all of the required data like product information, pricing information, and supply data, however for very long time, I’m utilizing CountDownLatch for such form of requirement. 

Associated Java multithreading Tutorials from Javarevisited Weblog

Thanks for studying this text of far. In case you discover this Java thread be part of tutorial helpful then please share it with your folks and colleagues. In case you have any
questions or suggestions then please drop a word. 

P. S. – If you’re eager to degree up your multithreading and concurrency abilities and in search of finest sources like on-line programs to essentially take your multithreading ability to subsequent degree then I extremely advocate these finest Java concurrency and multithreading programs for knowledgeable builders to begin watching. They’re nice to not solely be taught threads higher but in addition discover ways to apply that data in actual world. 
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments