java线程的join分析

要分析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();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值