您的位置:首页 > 编程语言 > Java开发

关于Java多线程Thread的join用法

2015-11-27 17:11 691 查看
多线程和子线程,我们称调用者为主线程,而被调用者为多线程。

主线程中开启子线程后,如果没有其他操作,则主线程可能会优先子线程执行完成。

场景:主线程中开启了子线程,在主线程退出之前需要调用子线程执行结果,这时候我们就需要用到join()操作。

设计一个源码测试下运行结果

设计子线程,SubThread.java

public class SubThread extends Thread {

int loopSeconds;

public SubThread(String threadName,int loopSeconds) {
super(threadName);
this.loopSeconds = loopSeconds;
}

@Override
public void run() {

int i = 0;

while(i<loopSeconds){
i++;

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread().getName()+"loop "+i);
}

}
}
场景一:在主线程main函数开启子线程
public class Main {

public static void main(String[] args) throws InterruptedException {

SubThread ct = new SubThread("[Thread A]",5);
ct.start();

ct.join();

System.out.println("Main thread exit");
}

}控制台打印结果:

[Thread A]loop 1
[Thread A]loop 2
[Thread A]loop 3
[Thread A]loop 4
[Thread A]loop 5
Main thread exit
有次可知,子线程A在调用join操作后,主线程在等起全部执行结束后完成执行。

场景二:下面我们创建2个子线程A和B,测试下多个线程下有一个执行join操作时,各自的调用顺序。其中A线程执行join操作,B线程不执行
public class Main {

public static void main(String[] args) throws InterruptedException {

SubThread ct = new SubThread("[Thread A]",3);
ct.start();
ct.join();

SubThread ct2 = new SubThread("[Thread B]",2);
ct2.start();

System.out.println("Main thread exit");
}

}打印结果:

[Thread A]loop 1
[Thread A]loop 2
[Thread A]loop 3
Main thread exit
[Thread B]loop 1
[Thread B]loop 2
线程A在启动后,立即开启了join操作,则线程B需要等到A全部执行完毕,主线程退出后才开始执行。

场景三:子线程A和B,在开启时,立刻执行join操作。
public class Main {

public static void main(String[] args) throws InterruptedException {

SubThread ct = new SubThread("[Thread A]",3);
ct.start();
ct.join();

SubThread ct2 = new SubThread("[Thread B]",2);
ct2.start();
ct2.join();

System.out.println("Main thread exit");
}

}
打印结果:

[Thread A]loop 1
[Thread A]loop 2
[Thread A]loop 3
[Thread B]loop 1
[Thread B]loop 2
Main thread exit
线程B需要等线程A全部执行完毕,才开始执行。两个子线程都执行完毕后,主线程才退出。

场景四:线程A和B同时开启后,再调用join操作。
public class Main {

public static void main(String[] args) throws InterruptedException {

SubThread ct = new SubThread("[Thread A]",3);
ct.start();

SubThread ct2 = new SubThread("[Thread B]",2);
ct2.start();

ct.join();
ct2.join();

System.out.println("Main thread exit");
}

}
打印结果:

[Thread A]loop 1
[Thread B]loop 1
[Thread A]loop 2
[Thread B]loop 2
[Thread A]loop 3
Main thread exit
线程A和B同时执行,等执行时间较长的子线程执行完毕,主线程才退出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: