Analysis of Thread join () method

  join Thread in () method in the actual development process may be used not many, but a solid knowledge of basic skills as a study in the interview or not, will often be used. Therefore, for the Thread of the join () method for a certain amount of research.

 

  How to ensure a common scenario is to create multiple threads to ensure their implementation in a specific order, the easiest method is to use Thread.join () method to achieve. The following is an example of code creates a number of threads written, achieved by using a creating entity class, which override its run method. If you specify the number of threads minority, can be directly used thread.join () to achieve, the principle is the same.

 1 public class Demo extends Thread{
 2     int i;
 3     Thread previousThread;
 4     public Demo3(int i, Thread previousThread) {
 5         this.i = i;
 6         this.previousThread = previousThread;
 7     }
 8 
 9     @Override
10     public void run(){
11         try {
12             previousThread.join();
13         } catch (InterruptedException e) {
14             e.printStackTrace();
15         }
16         System.out.println("顺序:"+i);
17     }
18 
19     public static void main(String[] args) {
20         Thread previousThread = Thread.currentThread();
21         for (int i=0; i<10; i++){
22             Demo3 demo3 = new Demo3(i, previousThread);
23             demo3.start();
24             previousThread = demo3;
25         }
26 
27     }
28 
29 }

 

  The code implements the business logic needs want, then the principle of what is it? The old rules, see the source code.

   

   

  We can see that it is fundamental to ensure the use of wait () method in the order of execution of multiple threads. When millis is 0, indicating that neither blocking time by isAlive () method of determining a viable state of the thread; if viable, it waits. Only when this thread does not survive, it will stop blocking, which is to ensure the order of execution threads. Note the need, because the call to wait () method, so it must be synchronized modified to ensure synchronization on the method level.

 

Guess you like

Origin www.cnblogs.com/Demrystv/p/11519748.html