1.Thread中的join()
join()把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
t.join(); //使调用线程 t 在此之前执行完毕。
t.join(1000); //等待 t 线程,等待时间是1000毫秒
2.为什么要用join()方法
主线程生成并起动了子线程,而子线程里要进行大量的耗时的运算,当主线程处理完其他的事务后,需要用到子线程的处理结果,这个时候就要用到join();方法了。
3.JDK源码
public final synchronized void join(long paramLong) throws InterruptedException{
long l1 = System.currentTimeMillis();
long l2 = 0L;
if (paramLong < 0L) {
throw new IllegalArgumentException("timeout value is negative");
}
if (paramLong == 0L) {
while (isAlive()) {
wait(0L);
}
}
while (isAlive())
{
long l3 = paramLong - l2;
if (l3 <= 0L) {
break;
}
wait(l3);
l2 = System.currentTimeMillis() - l1;
}
}
从代码上看,如果线程被生成了,但还未被起动,调用它的 join() 方法是没有作用的,将直接继续向下执行。
4.举例说明
public class ThreadJoin implements Runnable{
public static int num = 0;
public void run() {
for (int k = 0; k < 3; k++) {
num = num + 1;
}
}
public static void main(String [] args) throws InterruptedException{
Runnable r = new ThreadJoin();
Thread t = new Thread(r);
t.start();
System.out.println(num);
}
}
上面程序的输出结果不确定,通常情况下都不是3。为什么呢?当主线程 main方法执行System.out.println(num);这条语句时,子线程还没有真正开始运行,或许正在为它分配资源准备运行。因为为线程分配资源需要时间,而main方法执行完t.start()方法后继续往下执行System.out.println(num);这个时候得到的结果是num还没有被改变的值0 。怎样才能让输出结果为3!其实很简单,join() 方法提供了这种功能。join() 方法,它能够使调用该方法的线程在此之前执行完毕。
public static void main(String [] args) throws InterruptedException{
Runnable r = new ThreadJoin();
Thread t = new Thread(r);
t.start();
t.join(); //加入join()
System.out.println(num);
}
这个时候,程序输入结果始终为3
join(n)方法
public class ThreadJoin implements Runnable{
public static int num = 0;
public void run() {
try {
System.out.println("run start");
Thread.sleep(2000);
System.out.println("run end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String [] args) throws InterruptedException{
Runnable r = new ThreadJoin();
Thread t = new Thread(r);
t.start();
t.join(1);
System.out.println(num);
}
}
执行结果
run start
0
run end
分析:main线程只等1毫秒,不管子线程什么时候结束。这里特别注意:t.join(0); 当参数为0时,和没有参数的效果是一样的。因为从下面源码可以说明。
public final void join()
throws InterruptedException
{
join(0L);
}
欢迎大家积极留言交流学习心得,点赞的人最美丽,谢谢!