Thread.join()的含义及用法

理解join()方法的含义,我们借助图形来理解,有下面的场景:

image

  ThreadA启动ThreadB,然后调用ThredB.join()方法,这个时候,ThreadA会被阻塞,直到ThreadB运行结束,ThreadA才继续往下执行。

  看下面的例子,一目了然。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.zhuzp.test.concurrence;
public class JoinLearn {
/**
* @param args
*/
public static void main(String[] args) {
joinThread();
runInMain();
}
private static void joinThread(){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("i: " + i);
}
}
});
t.start();
}
private static void runInMain(){
for (int i = 0; i < 100; i++) {
System.out.println("runInMain: " + i);
}
}
}

  joinThread()方法中没有调用t.join,只是启动了线程t。看下结果(部分结果):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
runInMain: 0
i: 0
i: 1
runInMain: 1
runInMain: 2
runInMain: 3
runInMain: 4
runInMain: 5
runInMain: 6
runInMain: 7
runInMain: 8
runInMain: 9
runInMain: 10
runInMain: 11
runInMain: 12
runInMain: 13
runInMain: 14
runInMain: 15
runInMain: 16
runInMain: 17
runInMain: 18
runInMain: 19
runInMain: 20
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7

这种结果很容易理解。主线程中启动了一个子线程,然后继续往下执行了。然后看下如果调用了join()的结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.zhuzp.test.concurrence;
public class JoinLearn {
/**
* @param args
*/
public static void main(String[] args) {
joinThread();
runInMain();
}
private static void joinThread(){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("i: " + i);
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void runInMain(){
for (int i = 0; i < 100; i++) {
System.out.println("runInMain: " + i);
}
}
}

  部分结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
i: 84
i: 85
i: 86
i: 87
i: 88
i: 89
i: 90
i: 91
i: 92
i: 93
i: 94
i: 95
i: 96
i: 97
i: 98
i: 99
runInMain: 0
runInMain: 1
runInMain: 2
runInMain: 3
runInMain: 4
runInMain: 5
runInMain: 6
runInMain: 7
runInMain: 8
runInMain: 9
runInMain: 10
runInMain: 11
runInMain: 12
runInMain: 13
runInMain: 14

当主线程调用子线程的join()方法后,主线程被阻塞,处于等待的状态,等到子线程执行完成后,才继续往下执行。所以就有上面的结果了。是不是很easy 呢。