多线程中的join方法
join主要的作用就是让主线程 等待 子线程 执行完毕之后,才让主线程继续执行。 话不多说,直接看代码例子就好。
父线程
package com.luoy.Thread.join;
public class FatherThread implements Runnable{
@Override
public void run(){
// TODO Auto-generated method stub
System.out.println("父线程:我只要执行1秒钟。");
Thread son = new Thread( new SonThread());
son.start();
System.out.println("父线程:执行完毕。");
}
}
子线程
package com.luoy.Thread.join;
public class SonThread implements Runnable{
@Override
public void run(){
// TODO Auto-generated method stub
System.out.println("子线程:我要执行5秒钟。");
try{
for(int i = 0; i < 5; i++){
System.out.println(i+1);
Thread.sleep(1000);
}
}catch(InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("子线程:执行完毕。");
}
}
执行父线程
public static void main(String[] args){
System.out.println("主线程:开始执行");
Thread fa = new Thread(new FatherThread());
fa.start();
System.out.println("主线程:执行完毕");
}
看结果
主线程:开始执行
主线程:执行完毕
父线程:我只要执行1秒钟。
父线程:执行完毕。
子线程:我要执行5秒钟。
1
2
3
4
5
子线程:执行完毕。
由结果知道,1,主线程 执行完,2 父线程执行完,3子线程执行完。
我们使用join 方法之后的代码、
子线程代码不变,
父线程代码
package com.luoy.Thread.join;
public class FatherThread implements Runnable{
@Override
public void run(){
// TODO Auto-generated method stub
System.out.println("父线程:我只要执行1秒钟。");
Thread son = new Thread( new SonThread());
son.start();
try{
son.join();
}catch(InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("父线程:执行完毕。");
}
}
主线程代码
public static void main(String[] args){
System.out.println("主线程:开始执行");
Thread fa = new Thread(new FatherThread());
fa.start();
try{
fa.join();
}catch(InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("主线程:执行完毕");
}
再看结果
主线程:开始执行
父线程:我只要执行1秒钟。
子线程:我要执行5秒钟。
1
2
3
4
5
子线程:执行完毕。
父线程:执行完毕。
主线程:执行完毕
这样就看明白了,都会等待子线程执行完成,才继续执行