最近在编程遇到了个需要异步执行的操作,经过了一番折腾,发现在主子线程 操作中join()方法是非常实用且有效的一个方法.
先来看join()及其重载(overload)方法的说明和代码:
join()方法:
1 /**
2 * Waits for this thread to die.
3 *
4 * @exception InterruptedException if another thread has interrupted
5 * the current thread. The <i>interrupted status</i> of the
6 * current thread is cleared when this exception is thrown.
7 */
8 public final void join() throws InterruptedException {
9 join(0);
10 }
join(long millis)方法:
1 /**
2 * Waits at most <code>millis</code> milliseconds for this thread to
3 * die. A timeout of <code>0</code> means to wait forever.
4 *
5 * @param millis the time to wait in milliseconds.
6 * @exception InterruptedException if another thread has interrupted
7 * the current thread. The <i>interrupted status</i> of the
8 * current thread is cleared when this exception is thrown.
9 */
10 public final synchronized void join(long millis) throws InterruptedException {
11
12 long base = System.currentTimeMillis();
13 long now = 0;
14
15 if (millis < 0) {
16 throw new IllegalArgumentException ("timeout value is negative");
17 }
18
19 if (millis == 0) {
20 while (isAlive()) {
21 wait(0);
22 }
23 } else {
24 while (isAlive()) {
25 long delay = millis - now;
26 if (delay <= 0) {
27 break;
28 }
29 wait(delay);
30 now = System.currentTimeMillis () - base;
31 }
32 }
33 }