java线程的join分析

来源:互联网 发布:疯狂的赛车结局 知乎 编辑:程序博客网 时间:2024/05/19 09:02

要分析join方法原理,最简单直接的方式就是查看Thread源码,其中join() 方法的注释写到:Waits for this thread to die.(就是一直等到线程结束)。

由此可知join()方法具备的功能有:
- 线程start()之后才起作用
- 线程结束才退出
- 阻塞调用的线程

为了能更深入理解,以下是源码片段:

/**     * Waits for this thread to die.     *     * <p> An invocation of this method behaves in exactly the same     * way as the invocation     *、     * @throws  InterruptedException     *if any thread has interrupted the current thread. The     *  interrupted status of the current thread is     *  cleared when this exception is thrown.     */    public final void join() throws InterruptedException {        join(0);    }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;            }        }    }

从源码可以分析出

  1. join获取到了线程的锁;
  2. 通过wait()方法实现;
  3. 线程运行的时候(通过isAlive()方法判断),调用方就会一直阻塞住;
  4. 线程结束后会唤醒wait方法,并且isAlive()返回false,所以join()方法会结束退出;

如果要自己实现等价的功能可如下:

        synchronized (t) { // t 为线程            while (t.isAlive())                t.wait();        }
原创粉丝点击