http://blog.itpub.net/31555134/viewspace-2221319/
一直對join()方法不是很理解,在A線程中, B線程調用了join()方法,然后在內部實際是wait()方法,但是在效果上是A線程一直在等待,對wait()方法的調用不是很理解。(希望有朋友能夠給我答疑 非常感謝)
join()方法的作用是使所屬的線程對象x正常執行run()方法中的任務,而使當前線程z進行無限期的阻塞,等待線程x銷毀后再繼續執行線程z后面的代碼。方法join具有使線程排隊運行的作用,有些類似同步的運行效果。
下面是join()方法源碼:
/** * Waits for this thread to die. * * <p> An invocation of this method behaves in exactly the same * way as the invocation * * <blockquote> * {@linkplain #join(long) join}{@code (0)} * </blockquote> * * @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. */ public final void join() throws InterruptedException { join(0); }
/** * Waits at most {@code millis} milliseconds for this thread to * die. A timeout of {@code 0} means to wait forever. // 0意味着永遠等待不是等待0秒 millis意味着只等待millis,超過這個時間則停止等待 * * <p> This implementation uses a loop of {@code this.wait} calls * conditioned on {@code this.isAlive}. As a thread terminates the //當線程終止時, 會自動調用notifyall()方法 * {@code this.notifyAll} method is invoked. It is recommended that * applications not use {@code wait}, {@code notify}, or * {@code notifyAll} on {@code Thread} instances. * * @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. */ 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; } } }
當然了, join()方法放在start()方法后面才會有效果。