关于java中的join()方法

javadoc是这样写的

public final void join()
                throws InterruptedExceptionWaits for this thread to die. 
An invocation of this method behaves in exactly the same way as the invocation 

join(0) 
Throws: 
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown. 

可以看到这是一个阻塞方法,并且可以响应中断。

join()方法实现大致是使用了一个while循环一直判断当前线程是否存活,如果存活的话,调用wait()方法,使线程进入WAITING状态;当线程终止时,jvm会自动调用它的notifyAll()方法(在jdk源码中看不到,应该在jvm源码中),将其唤醒,此时isAlive方法返回false,方法执行完成。

相当于把一个线程对象当做监视器锁用了。

同时join(long)方法还可以传入一个超时等待时间,避免过长时间的阻塞。

此方法的实现如下:

public final void join() throws InterruptedException {
        join(0);
}
public final void join(long millis)
                throws InterruptedException
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. 
This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Parameters: 
millis - the time to wait in milliseconds 
Throws: 
IllegalArgumentException - if the value of millis is negative 
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 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值