join的三个重载方法
(1)public final void join(long millis) throws InterruptedException
(2)public final void join(long millis, long nanos) throws InterruptedException
(3)public final void join() throws InterruptedException
区别:join()== join(0) ; (2)等待millis微秒加上nanos纳秒。
文档翻译
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
等待这个线程死掉,最多等millis微秒。如果millis是0,表示永远等待。
This implementation uses a loop ofthis.wait calls conditioned onthis.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.
这个实现使用了一个循环,循环条件是this.isAlive,循环体是this.wait。。当一个线程终止,this.notifyAll方法被调用。强烈建议应用程序不要使用线程实例的wait,notify或者notifyAll。
异常
IllegalArgumentException - if the value of millis is negative
如果millis的值是负数
InterruptedException -
if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
如果任何其他线程中断了当前线程。当这个异常被抛出后,当前线程的中断状态被清除。
join使用场景举例
在主线程A中启动子线程B。
B.start();
B.join(0);
调用B.join(0)之后,A线程就会进入等待状态,直到B结束(B会调用notifyAll)。
下面给出Jetty的示例代码:
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
server.setHandler(new HelloHandler());
server.start();
server.join();
}
join源码
if(millis == 0){ (1)
while(isALive()){ (2)
wait(0); (3)
}
}
解读一下这几行代码:
(1)如果millis等于0,表示调用线程(A线程)将一直等待子线程,直到子线程B结束。
(2)isAlive方法是子线程B的方法,返回子线程的当前状态。
(3)wait(0)是Object的方法,A线程对象将进入B对象的waiting set,直到B线程对象终止。
wait的文档是这样的:
Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
wait的效果是导致当前线程进入等待状态,由于这段代码是在主线程中调用的,所以导致主线程进入等待。