1 背景
在进行面试的时候,当被问及如何保证线程的执行顺序的时候,大部分人可能都想到使用join保证顺序。面试官微微一笑,那么你知道join原理是什么吗?额。。。
示例代码
public class TestJoin {
public static void main(String[] args) {
int count = 1000;
Task t1 = new Task(count, null);
t1.setName("t1");
Task t2 = new Task(count, t1);
t2.setName("t2");
t2.start();
t1.start();
}
public static class Task extends Thread {
private final int count;
private Task task;
public Task(int count, Task task) {
this.count = count;
this.task = task;
}
@Override
public void run() {
if (task != null) {
try {
task.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < count; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
Thread.yield();
}
}
}
}
如上代码所述,线程t2中调用了t1的join方法。那么t2就需要等待t1执行完循环之后再执行自己的循环。
2 原理
2.1 线程等待
点击进入join方法,查看源码会看到如下的内容
源码1
这明显还不够,继续深入
源码2
因为我的join方法,未传入参数,那么也就是走的红框中的部分。也就是会无限期等待,直到线程t1执行完成才能执行t2。
再看看方法wait(0),点击去之后,发现这个方法其实就是Object的方法,且跟我们调用对象的wait()方法调用的是同一个方法。
object中的wait方法
而我们在调用wait()方法的时候是必须先要获取锁的,那么根据wait()的调用可知wait(0)方法的调用也必须要先获取锁的。
回到join方法,这里我们没有看到同步块,但是看到方法的修饰词中出现了synchronized,那么就知道这里其实是获取锁了。锁对象就是调用了join的那个对象。在示例代码中就是在线程t2中调用了线程t1的join方法,那么需要被阻塞的就是t2线程,而锁对象就是t1对象。
2.2 线程唤醒
好了,现在线程t2的等待问题明白了。那么t2是如何被唤醒的呢。因为我们自己使用的时候都是wait和notify/notifyAll成对出现的。否则线程将无限期等待下去。如果等待线程还是一个非守护线程。那么就会导致程序不能正常结束。
在我找了半天程序,就是没有看到在哪里进行的唤醒。最后自己想了想是不是在线程销毁的时候,去看了下Thread类有没有重写finalize()方法,但是可惜不是这里。而且也不能是这里。因为执行finalize()方法的线程是一个低优先级的线程,同时需要垃圾回收t1,而且线程还不保证一定会执行finalize()。所以不能放在这里。没办法,网上找了下资料,果然大佬还是多。传送门。这里找到了答案。由于本人这里暂时没有jvm源码,也就copy了下这位大神的东西了。
还是在线程执行完毕,不过这次是jvm底层会去做一些校验
// 位于/hotspot/src/share/vm/runtime/thread.cpp中
void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
// ...
// Notify waiters on thread object. This has to be done after exit() is called
// on the thread (if the thread is the last thread in a daemon ThreadGroup the
// group should have the destroyed bit set before waiters are notified).
// 有一个贼不起眼的一行代码,就是这行
ensure_join(this);
// ...
}
static void ensure_join(JavaThread* thread) {
// We do not need to grap the Threads_lock, since we are operating on ourself.
Handle threadObj(thread, thread->threadObj());
assert(threadObj.not_null(), "java thread object must exist");
ObjectLocker lock(threadObj, thread);
// Ignore pending exception (ThreadDeath), since we are exiting anyway
thread->clear_pending_exception();
// Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
// Clear the native thread instance - this makes isAlive return false and allows the join()
// to complete once we've done the notify_all below
java_lang_Thread::set_thread(threadObj(), NULL);
// 同志们看到了没,别的不用看,就看这一句
// thread就是当前线程,是啥?就是刚才例子中说的t1线程啊。
lock.notify_all(thread);
// Ignore pending exception (ThreadDeath), since we are exiting anyway
thread->clear_pending_exception();
}
当线程t1执行完毕是,jvm在关闭线程之前会检测线阻塞在t1线程对象上的线程,然后执行notfyAll(),这样t2就被唤醒了。
3 总结:
1.创建线程t1和t2.
2.启动线程t1和t2
3.在线程t2中调用线程t1的join方法
4.线程t2获取到t1对象上的锁,然后执行wait()无限期等待
5.t1执行业务代码
6.t1执行完毕,在关闭t1之前,jvm唤醒所有阻塞在t1对象上的线程
7.t2被唤醒,继续执行
8.t2结束。