自从接触Java多线程,一直对Join理解不了。JDK是这样说的:join 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.大家能理解吗? 字面意思是等待一段时间直到这个线程死亡,我的疑问是那个线程,是它本身的线程还是调用它的线程的,上代码:
} 结果是: Begin sleep joinFinish End sleep 也就是说main线程只等1000毫秒,不管T什么时候结束,如果是t.join()呢, 看代码: public final void join() throws InterruptedException { join(0); } 就是说如果是t.join() = t.join(0) 0 JDK这样说的 A timeout of 0 means to wait forever 字面意思是永远等待,是这样吗? 其实是等到t结束后。 这个是怎么实现的吗? 看JDK代码:
/** * Waits at most <code>millis</code> milliseconds for this thread to * die. A timeout of <code>0</code> means to wait forever. * * @param millis the time to wait in milliseconds. * @exception 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. */ publicfinalsynchronizedvoid join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now =0;
if (millis <0) { thrownew 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; } } }