join()的作用是:“等待该线程终止”,这里需要理解的就是该线程是指的主线程等待子线程的终止。
也就是在子线程调用了join()方法后面的代码,只有等到子线程结束了才能执行。
public final void join(long millis, int nanos) throws InterruptedException
public final void join(long millis) throws InterruptedException
public final void join() throws InterruptedException //其实调用了 join(0), 0 意味着永远等待。
join()方法的本质是让调用线程wait()在当前线程对象的实例上,JDK中的源码片段
public final synchronized void join(long millis)
// 省略...
while (isAlive()) {
wait(0);
}
当线程执行完成后,被等待的线程会在退出前调用notifyAll()通知所有的等待线程继续执行。
因此,建议在应用程序中,在Thread对象实例上不要使用wait()、notify()或 notifyAll() 方法,以避免可能出现的影响系统api或者被系统所影响。
/**
* 这个demo为了演示加join()与不加的效果
* @author MatrixOne001
*/
public class Join {
public volatile static int sum = 0 ;
public static class AddThread extends Thread{
@Override
public void run() {
for( sum=0; sum<1000000; sum++ );
}
}
public static void main(String[] args) throws InterruptedException {
AddThread at = new AddThread();
at.start();
at.join(); //如果不加这行代码,输出sum的值很有可能为0或者比1000000小的数字
System.out.println( sum );
}
}