java 线程结束做了什么?

public class ThreadA extends Thread{

    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            //
        }
        System.out.println("exit");
    }

    public static void main(String[] args) throws Throwable {
        Thread a = new ThreadA();
        a.start();
        synchronized (a){
            a.wait();
        }
        System.out.println("end");
        //end会输出,到底是谁唤醒的,是线程exit里面的notifyAll方法吗?并不是,那个是线程组的。
    }
}

https://blog.csdn.net/yibei8811/article/details/52328026

其中14.1.3条件队列,我摘了部分JDK代码,其实理解不对。

因为代码的中的notifyAll()中的this是Threadgroup。

线程的确会被调用notifyAll(),但是不是这里,而是在C中,这篇文章应该可靠。

https://segmentfault.com/q/1010000016744022

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);
  lock.notify_all(thread);
  // Ignore pending exception (ThreadDeath), since we are exiting anyway
  thread->clear_pending_exception();
}

 

你可能感兴趣的:(java)