回忆一个加塞方法

Thread.join()用来让当前线程插队。

 1     static Thread main;
 2     static Thread threadA;
 3     static Thread threadB;
 4     
 5     public static void main(String[] args) throws InterruptedException {
 6         main = Thread.currentThread();
 7         
 8         for (int i = 0; i < 10; i++) {
 9             System.out.println("Main " + i);
10             
11             if (i == 5) {
12                 threadA = new Thread(new RunnerA());
13                 threadA.start();
14                 threadA.join();
15             }
16         }
17     }
18     
19     public static class RunnerA implements Runnable {
20         public void run() {
21             for (int j = 0; j < 10; j++) {
22                 System.out.println("A " + j);
23                 
24                 if (j == 5) {
25                     threadB = new Thread(new RunnerB());
26                     threadB.start();
27                     try {
28                         threadB.join();
29                     } catch (InterruptedException e) {}
30                 }
31             }
32         }
33     }
34     
35     public static class RunnerB implements Runnable {
36         public void run() {
37             for (int j = 0; j < 10; j++) {
38                 System.out.println("BB " + j);
39             }
40         }
41     }

上面的代码中,主线程打印数字到5的时候被A线程插队,A线程打印到5的时候又被B线程插队,等到BA依次打印完之后主线程才继续打印6到9。

如果把B线程的加塞语句移到A线程for循环结束之后或主线程中A线程的加塞语句之后执行,则主线程打印到5之后AB会依次打印0到9,然后再轮到主线程。

一个思考题。

如果把A线程中的加塞语句改成下面这样:

if (j == 5) {try {
        main.join();
    } catch (InterruptedException e) {}
}

那么主线程和A线程都只打印到5程序就结束了。

为什么?

原文地址:https://www.cnblogs.com/chihane/p/4535055.html