等待线程终止
在有的时候,需要等待一个线程执行完后才能继续执行后面的程序;比如资源的加载,只有当加载完所有的资源后,在继续执行业务逻辑部分;那么Thread类的join方法,Thread.join()就起这个作用; 当一个线程使用一个线程对象调用了join()方法,那么这个线程对象将会被挂起,直到这个线程对象执行完毕后,调用线程才会继续执行;
动手实现
public class ResourceLoader implements Runnable { //模拟资源加载 @Override public void run() { System.out.printf("Beginning data sources loadding:%s\n", new Date()); try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Data source loading has finished:%s\n", new Date()); } public static void main(String[] args) { Thread thread1 = new Thread(new ResourceLoader(), "localResourceLoader"); Thread thread2 = new Thread(new ResourceLoader(), "remoteResourceLoader"); thread1.start(); thread2.start(); //主线程等待资源加载完毕 try { thread1.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Main:Resource has been loaded:%s\n", new Date()); }}一次运行结果:
Beginning data sources loadding:Fri Oct 31 00:09:37 CST 2014
Beginning data sources loadding:Fri Oct 31 00:09:37 CST 2014 Data source loading has finished:Fri Oct 31 00:09:41 CST 2014 Data source loading has finished:Fri Oct 31 00:09:41 CST 2014 Main:Resource has been loaded:Fri Oct 31 00:09:41 CST 2014要点
Java提供了两个方法
- join(long milliseconds)
- join(long milliseconds,long nanos)
第二个方法接受两个参数,毫秒,纳秒
join方法是Thread类非静态方法