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
主线程继续。。。。
Votre question a reçu une réponse ci-dessus. notifyAll sera appelé à la fin du fil de discussion.
La couche inférieure de la JVM utilise en fait l'API fournie par la couche du système d'exploitation pour prendre en charge les threads. Par exemple, les systèmes d'exploitation de type UNIX utilisent généralement pthread (Windows a également l'implémentation hotspotVM d'Openjdk qui utilise pthread). Version openjdk8. Le code réel sous-jacent à hotspotVM.
Lorsque Thread exécute la méthode start, il appellera le start0 de la méthode native. La couche inférieure de start0 est en fait encapsulée dans plusieurs couches, et enfin la méthode createJavaThread sera appelée pthread_create pour créer un thread et. exécutez-le.
Le processus est à peu près comme ceci : Thread.start() -> start0() -> createJavaCreate() -> ) -> Exécuter run() de Thread -> detachThread() "Cette méthode appellera enfin Object.notifyAll".
openjdk-8-8u66-b17/jamvm-2.0.0/src/thread.c
Votre inférence doit être correcte. Lorsqu'un thread meurt, il appellera sa propre méthode notifyAll
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