跳至主要內容
Java 并发编程笔记

Thread.join()

cThread.join()方法使当前线程阻塞,直到子线程cThread执行完毕后,当前线程才会恢复运行。

实现原理:

  1. join()方法调用了join(0)

    public final void join() throws InterruptedException {
        join(0);
    }
    
  2. join(long millis)是一个同步方法,最后会通过调用wait()方法挂起当前线程(即调用线程),直到其他线程调用子线程cThreadnotify()或者notifyAll()方法

    public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;
    
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }
    
        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }
    
  3. 子线程run()执行完毕后,系统在关闭该子线程前,会调用其exit()方法,继而在ThreadGroup.threadTerminated(Thread t)中唤醒被阻塞的调用线程。

    /**
     * This method is called by the system to give a Thread
     * a chance to clean up before it actually exits.
     */
    private void exit() {
        if (group != null) {
            group.threadTerminated(this);//提心 ThreadGroup 当前线程已经被终止
            group = null;
        }
    
        //其他代码 ……
    }
    
    // ThreadGroup
    void threadTerminated(Thread t) {
        synchronized (this) {
            remove(t);
    
            if (nthreads == 0) {//线程组线程数为0时
                notifyAll();//唤醒所有等待中的线程
            }
            if (daemon && (nthreads == 0) &&
                (nUnstartedThreads == 0) && (ngroups == 0))
            {
                destroy();
            }
        }
    }
    

JI,XIAOYONG...大约 2 分钟java