Thread类的join方法的源代码:
/**
* 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.
*/
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;
}
}
}
Thread join 方法实例代码如下:
package nc.com.thread.traditional.example;
/**
* @ClassName: ThreadJoin
* @Description: TODO(这里用一句话描述这个类的作用)
* @author A18ccms a18ccms_gmail_com
* @date 2015-12-19 下午06:35:15
*
*/
public class ThreadJoin {
private Object object = new Object();
private int i = 10;
public static void main(String[] args) {
/**
* 有join时输出:
*/
ThreadJoin j = new ThreadJoin();
DemoThread t1 = j.new DemoThread();
t1.start();
try {
//执行join方法后,主线程进入阻塞状态,直到子线程执行结束
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("----------主线程已经等到了子线程执行结束,继续执行主线程--------");
}
class DemoThread extends Thread{
@Override
public void run() {
synchronized (object) {
i++;
System.out.println("i:"+i);
try {
System.out.println("线程"+Thread.currentThread().getName()+"进入睡眠状态");
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("线程"+Thread.currentThread().getName()+"睡眠结束");
i++;
System.out.println("i:"+i);
}
}
}
}
输出:
i:11
线程Thread-0进入睡眠状态
线程Thread-0睡眠结束
i:12
----------主线程已经等到了子线程执行结束,继续执行主线程--------