按照惯例先吟诗一首:

送崔九
唐代:裴迪
归山深浅去,须尽丘壑美。
莫学武陵人,暂游桃源里。

join()方法的作用是等待线程销毁。例如在main线程新起一个子线程,子线程需要做一些耗时造作,main线程想要得到子线程执行完成的数据,就必须等到执行完子线程再去执行,这时候就可以用join来解决。

基本使用

下面用代码来说明:

MyThread类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyThread04 extends Thread{
@Override
public void run() {
try{
int value=(int)(Math.random()*1000);
System.out.println("thread04 value="+value);
Thread.sleep(value);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}

YieldTest类

1
2
3
4
5
6
7
8
9
10
11
12
13
public class JoinTest {
public static void main(String[] args){
MyThread04 thread04=new MyThread04();
thread04.start();
// try {
// thread04.join();
// }catch (InterruptedException e){
// e.printStackTrace();
// }
System.out.println("我想在thread04之后执行");
}
}

结果如下:

我想在thread04之后执行
thread04 value=8

从结果上看,主线程和子线程是异步的,并没有在子线程执行完之后才执行,而是在子线程执行过程中就执行了主线程。如果想要实现同步的话,需要用到join()方法

将MyThread03类更改一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class JoinTest {
public static void main(String[] args){
MyThread04 thread04=new MyThread04();
thread04.start();
try {
thread04.join();
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("我想在thread04之后执行");
}
}

结果如下:

thread04 value=323
我想在thread04之后执行