java

join(),源码中的解释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Waits for this thread to die.

<p> An invocation of this method behaves in exactly the same
way as the invocation

<blockquote>
{@linkplain #join(long) join}{@code (0)}
</blockquote>

@throws InterruptedException
if any thread has interrupted the current thread. The
<i>interrupted status</i> of the current thread is
cleared when this exception is thrown.
/
public final void () throws InterruptedException {
join(0);
}

等待这个线程结束,也就是等待这个线程结束后再继续执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.king.learn;

public class MyJoin {
public static void main(String[] args) throws InterruptedException {
System.out.println("start");
Thread t=new Thread(()->{
for(int i=0;i<5;i++){
System.out.println(i);
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
}
});
t.start();
t.join();
System.out.println("end");
}
}

输出

1
2
3
4
5
6
7
start
0
1
2
3
4
end

如果没有t.join()阻塞,end可能会在0~5之间输出。说明t.join()阻塞了主线程直到t线程执行结束。

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
public final synchronized void (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;
}
}
}

使用wait(0)方法实现