1. 程式人生 > 其它 >java中當執行緒終止時,會呼叫自身的notifyAll方法的原理分析

java中當執行緒終止時,會呼叫自身的notifyAll方法的原理分析

例子程式碼

public class Client {

  public static void main(String[] args) throws InterruptedException {
    Thread thread = new Thread(() -> {
      System.out.println(Thread.currentThread().getName() + " run start");
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName() + " run end");
    });
    thread.start();
    thread.join();
    System.out.println(Thread.currentThread().getName() + " run end");
  }

}

主要是關於Thread.join()方法的用法,join()方法內部也是呼叫的wait()方法,
將當前執行緒也就是main執行緒阻塞住,但在這個過程沒有呼叫notify()和notifyAll()方法,
那main執行緒是什麼時候被喚醒的呢?

原理

這裡使用openjdk16的原始碼,其實各版本差別不大,github地址
主要原始碼都在 src/hotspot/share/runtime/thread.cpp 檔案中

void Thread::call_run() {
  ...
  this->pre_run();
  this->run();
  this->post_run();
  ...
}

void JavaThread::post_run() {
  this->exit(false);
  ...
}

void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
  ...
  ensure_join(this);
  ... 
}

static void ensure_join(JavaThread* thread) {
  ...
  lock.notify_all(thread);
  ...
}

可以看到線上程執行結束前會呼叫notifyAll()方法,喚醒所有等待的執行緒,示例程式碼中的main執行緒就是這樣被喚醒的。

參考

《Java併發程式設計的藝術》中關於“當執行緒終止時,會呼叫自身的notifyAll方法”?何以見得?