Java线程同步的Join()原理

在使用线程实现诸如A->B->C这样的时候,想到的无疑就是join()方法,看了一下方法的源码,然后也是各方搜集了一下资料才明白其中的原理,这篇文章就记录一下当时的困惑。
在我查看源码注释的时候,发现了两个线程this thread和current thread,this指的当然是调用方法的this对象的线程,而current却是指的是当前正在运行的线程,请注意他们的区别。

/**
     * Waits at most {@code millis} milliseconds for this thread to
     * die. A timeout of {@code 0} means to wait forever.
     *等待this线程死亡,参数0即代表如果不唤醒会一直等下去
     * <p> This implementation uses a loop of {@code this.wait} calls
     * conditioned on {@code this.isAlive}. As a thread terminates the
     * {@code this.notifyAll} method is invoked. It is recommended that
     * applications not use {@code wait}, {@code notify}, or
     * {@code notifyAll} on {@code Thread} instances.
     *这里实际上就已经提到了,所有线程都会在死亡的时候调用notifyAll方法唤醒所有阻塞在这个锁上的线程
     * @param  millis
     *         the time to wait in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
     //JDK1.8的join()方法
    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()) { //判断this线程是否存活,如果this线程已经执行完成死亡,那么current线程直接执行
           //并不会进入wait()方法
                wait(0); //开始我在这里纠结了一会儿,虽然是this线程调用等待,但是wait实际上是current线程进行阻塞
                //,也即是当前运行线程阻塞,注意是当前线程拿的这个锁那么也只有这个线程能释放锁
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值