1.首先通过源码可以看到join方法的底层逻辑还是使用当前线程对象的wait方法,也知道子线程执行完业务代码后,主线程才能解除阻塞。我认为既然使用的是wait方法,必然需要notify或notifyAll来唤醒,但唤醒的机制是什么?难道使用的线程的隐式钩子方式,当线程执行完后再进行notify?
2.伪代码,按自己的理解实现join方法,不知道这样对不对?
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
ThreadTest tt=new ThreadTest();
tt.start();
synchronized (tt) {
tt.wait();
}
System.out.println("主线程继续。。。。");
}
}
class ThreadTest extends Thread {
public void run() {
for(int i=0;i<5;i++){
try {
Thread.sleep(1000);
System.out.println("i="+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//---输出结果输下----
i=0
i=1
i=2
i=3
i=4
主线程继续。。。。
Your question has been answered above, notifyAll will be called when the thread ends.
The bottom layer of JVM actually uses the API provided by the OS layer to support threads. For example, UNIX-like OS generally uses pthread (Windows also has Pthread implementation). Openjdk’s hotspotVM uses pthread. Let’s take a look at the openjdk8 version of hotspotVM. The underlying actual code.
When Thread executes the start method, it will call the start0 of the native method. The bottom layer of start0 is actually encapsulated in many layers, and finally the createJavaThread method will be called. createJavaThread will call pthread_create to create a thread and execute it.
The process is roughly like this: Thread.start() -> start0() -> ... -> createJavaCreate() -> pthread_create() => threadStart() => attachThread() -> ; Execute Thread's run() -> detachThread() "This method will finally call Object.notifyAll".
openjdk-8-8u66-b17/jamvm-2.0.0/src/thread.c
Your inference should be correct. When a thread dies, it will call its own notifyAll method
As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
java/lang/Thread.java#1258