Interfering with the order of thread execution-the join method of the Thread class

I often hear such an interview question: How to ensure the order of execution of multiple threads?

There are many answers, such as the use CompletableFuture (JDK8 new), LookSupport tools, wait and notify, also had to write this article Thread.join () method

  1. The join() method of the Thread class can block the current thread. Assuming that the execution of thread A calls the join method of thread B, then thread A cannot continue to execute before thread B is executed. Note that it is waiting for the call The thread with the join() method is executed after the execution, so you cannot call your own join method when using it, which will cause the thread itself to wait and fail to execute.
  2. The join method of B is called in A, but A may not be executed immediately after B is executed . Because the inside of the join() method is actually the wait() method of the execution thread , wait() will release the lock and release the CPU, so the join method can only guarantee the execution order of the two threads that call the join method. If there are threads at the same time A, B, C, thread B call the join method of A, then after the three threads start, only B can be guaranteed to be executed after A thread is executed, but after A is executed and the CPU is released, C may also be executed before B (If C grabs the CPU or lock before B)

In the following code, thread1.join() is executed in thread2 and thread2.join() is executed in thread3. In this way, thread2 will wait for thread1 to finish executing, and thread3 will wait for thread2 to finish executing; finally in the main thread Call thread3.join() and wait for thread3 to finish executing.

Guess you like

Origin blog.csdn.net/qq_29569183/article/details/115029646