Execution order of threads in Java

        In multithreading, when multiple threads are started by calling Thread's start() method, the execution order of each thread is undefined. That is to say, after multiple threads are created continuously, the order in which the start() method is called does not determine the actual execution order of the threads.

        Write an example to verify:

public class Test {
    
    public static void main(String[] args){
        Thread thread1 = new Thread(() -> {
            System.out.println("Thread1");
        });
        Thread thread2 = new Thread(() -> {
            System.out.println("Thread2");
        });
        Thread thread3 = new Thread(() -> {
            System.out.println("Thread3");
        });
        thread1.start();
        thread2.start();
        thread3.start();
    }
    
}

        We create three different threads, thread1, thread2, and thread3, and then start the three threads by calling the thread1.start(), thread2.start(), and thread3.start() methods.

        Run the main method, the result is as follows:

thread1
thread2
thread3

When run again, the result is as follows:

Thread1
Thread3
Thread2

Note: Everyone's situation may be different.
Continue to repeat the run several times and find that the order of execution may be different for each run. Note that the order in which threads are started does not determine the order in which threads are executed .

How to ensure the execution order of threads

So how to ensure the execution order of threads?
The execution order of threads can be ensured by using the join() method in the Thread class.

Write another example to verify:

public class Test {
    
    public static void main(String[] args){
        Thread thread1 = new Thread(() -> {
            System.out.println("Thread1");
        });
        Thread thread2 = new Thread(() -> {
            System.out.println("Thread2");
        });
        Thread thread3 = new Thread(() -> {
            System.out.println("Thread3");
        });
        thread1.start();
        thread1.join();

        thread2.start();
        thread2.join();

        thread3.start();
        thread3.join();
    }
    
}

The result of the operation is as follows:

thread1
thread2
thread3

We repeated the operation several times and found that the results of each operation were the same. Therefore, using Thread's join() method can guarantee the order in which threads are executed.

Principle analysis:

Because calling the join() method of the child thread will block the execution of the main() method, the main() method will not continue to execute until the child thread is executed.

Guess you like

Origin blog.csdn.net/icanlove/article/details/46658851
Recommended