1、join()介绍
join()
定义在Thread.java
中。
join()
的作用:让主线程等待子线程结束之后才能继续运行。这句话可能有点晦涩,我们还是通过例子去理解:
// 主线程
public class Father extends Thread {
public void run() {
Son s = new Son();
s.start();
s.join();
...
}
}
// 子线程
public class Son extends Thread {
public void run() {
...
}
}
说明:
上面有两个类Father(主线程类)和Son(子线程类)。因为Son是在Father中创建并启动的,所以,Father是主线程类,Son是子线程类。
在Father主线程中,通过new Son()新建子线程s。接着通过s.start()
启动子线程s,并且调用s.join()
。在调用s.join()
之后,Father主线程会一直等待,直到子线程s运行完毕;在子线程s运行完毕之后,Father主线程才能接着运行。这也就是我们所说的join()
的作用,是让主线程等待子线程结束之后才能继续运行!
2、join()源码分析(基于JDK1.8.0_191)
public final void join() throws InterruptedException {
join(0);
}
public final synchronized void join(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;
}
}
}
说明:
从代码中,我们可以发现。当millis=0时,会进入while(isAlive())
循环,即只要子线程是活的,主线程就不停的等待。
我们根据上面解释join()
作用时的代码来理解join()
的用法!
问题:虽然s.join()被调用的地方是发生在Father主线程中,但是s.join()是通过子线程s去调用的join()。那么,join()方法中的isAlive()应该是判断子线程s是不是Alive状态;对应的wait(0)也应该是让子线程s等待才对。但如果是这样的话,s.join()的作用怎么可能是让主线程等待,直到子线程s完成为止呢,应该是让子线程等待才对(因为调用子线程对象s的wait方法嘛)?
答案:wait()的作用是让当前线程等待,而这里的当前线程是指当前在CPU上运行的线程。所以,虽然是调用子线程的wait()方法,但是它是通过主线程去调用的;所以,休眠的是主线程,而不是子线程
3、join()示例
在理解join()的作用之后,接下来通过示例查看join()的用法。
// JoinTest.java的源码
public class JoinTest{
public static void main(String[] args){
try {
ThreadA t1 = new ThreadA("t1"); // 新建“线程t1”
t1.start(); // 启动“线程t1”
t1.join(); // 将“线程t1”加入到“主线程main”中,并且“主线程main()会等待它的完成”
System.out.printf("%s finish\n", Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class ThreadA extends Thread{
public ThreadA(String name){
super(name);
}
public void run(){
System.out.printf("%s start\n", this.getName());
// 延时操作
for(int i=0; i <1000000; i++)
;
System.out.printf("%s finish\n", this.getName());
}
}
}
运行结果:
t1 start
t1 finish
main finish
结果说明:运行流程如图
1.在主线程main中通过 new ThreadA("t1")
新建线程t1。 接着,通过t1.start()
启动线程t1,并执行t1.join()
。
2. 执行t1.join()
之后,主线程main会进入阻塞状态等待t1运行结束。子线程t1结束之后,会唤醒主线程main,主线程重新获取cpu执行权,继续运行。
4、join的代替写法
public class JoinPrinciple {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行完毕");
}
});
thread.start();
System.out.println("开始等待子线程运行完毕");
//thread.join();
//当线程终止时,会调用自身的notifyAll方法
synchronized (thread) {
thread.wait();
}
System.out.println("所有子线程执行完毕");
}
}
下一章: 第八章 线程让步