The role and principle of join in Thread

tags: Thread

Article introduction
  1. Thread.join role
  2. The realization principle of Thread.join
  3. When will Thread.join be used
  4. Expand

1 role

In the case of multi-threading, each single thread is competing to obtain CPU execution rights. The order is first to be folded first. To ensure the execution order of sub-threads, the main thread is controlled through Thread.join so that the sub-threads are executed before the next sub-thread is executed. , The bottom realization principle uses wait in Object

dome1


public class ThreadJoin {

    static Thread thread1=new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread1");
        }
    });
    static Thread thread2=new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread2");
        }
    });
    static Thread thread3=new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread3");
        }
    });

    public static void main(String[] args) throws InterruptedException {
        thread1.run();
        thread1.join();
        thread2.run();
        thread1.join();
        thread3.run();
        thread3.join();
    }

}

Results of the :

thread1
thread2
thread3

Process finished with exit code 0

appear:
When thread.join(); is not added to the code, the order of them cannot be guaranteed in multi-threaded execution. The output result is out of order. It is necessary to execute after adding it.

principle

Refer to the figure below to understand the principle

View source code:

....
public final void join() throws InterruptedException {
        join(0);
}
    ....
 public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

Summary: When the main thread calls the run sub-thread, and the sub-thread calls join, the main thread will be blocked. You can see from the join source code that the synchronized, wait() method waits for the execution to complete and then executes the main thread to execute the second sub-thread to ensure the performance of each thread After execution, execute the next child thread

When is it used

When multi-threading is required, such as: t1, t2 threads, the result of t1 is needed to perform other business logic when executing t1, you can use Thread.join to wait for the sub-thread to execute and then do the following logical operations
Refer to deom2 for details

public void joinDemo(){
   //....
   Thread t=new Thread(payService);
   t.start();
   //.... 
   //Other business logic processing, no need to determine whether the t thread is executed
   insertData();
   //Follow-up processing depends on the execution result of t thread, you can call join method here to wait for the end of t thread execution
   t.join();
}

Expand

We can also achieve sequential execution through the FIFO method in the multi-threaded team
The idea is to use the thread pool Executors.newSingleThreadExecutor() in the single thread mode, the bottom layer uses FIFO (first in first out) to achieve multi-threaded orderly execution

Reference dome1 modification

 ExecutorService executorService=Executors.newSingleThreadExecutor();
        executorService.execute( thread1);
        executorService.execute( thread2);
        executorService.execute( thread3);
        executorService.isShutdown();

Consistent output

If there is any inappropriate understanding, welcome to complain~~

Intelligent Recommendation

Java multi -threaded Join () method of the role and implementation of principle analysis

Table of contents First, preface Second, common methods of threads Third, the role of the join () method 4. Principle of Join () method 5. Join () method source code question 6. Join () method of dead...

Thread ------ join thread join()

The join() method must be after the stat() method in order to work result...

join method principle java thread, and use daemon threads

1: effect of talk about the join method:The calling thread can join so that other threads waiting for the end of his run, other threads will continue to run. 2: Thread divided into two categories, the...

Detailed explanation of the principle of Python multithreading threading join and daemon thread setDeamon

Multiple threads in the same process share memory data, there is no primary and secondary relationship between multiple threads, and they can operate with each other; cpu executes threads, and the def...

More Recommendation

Concurrency --- join a thread join

join A thread can call the join() method on top of other threads. The effect is to wait for a while until the second thread ends before continuing execution. If a thread calls t.join() on another thre...

Join in the thread

Join in a Java threadIs using threads fromasynchronousExecution becomes synchronous execution. Join use example 1: use in a thread...

Thread join()

2019 Unicorn Enterprise Heavy Gold Recruitment Python Engineer Standard >>> package com.ztesoft.quartz_maven.quartz; public class Test { } Reprinted at: https://my.oschina.net/u/989066/blog/3...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top