(一)线程管理_5---等待线程终止

等待线程终止

在有的时候,须要等待一个线程执行完后才能继续执行后面的程序;好比资源的加载,只有当加载完全部的资源后,在继续执行业务逻辑部分;那么Thread类的join方法,Thread.join()就起这个做用; 当一个线程使用一个线程对象调用了join()方法,那么这个线程对象将会被挂起,直到这个线程对象执行完毕后,调用线程才会继续执行;java

动手实现

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
ide

要点

Java提供了两个方法线程

  1. join(long milliseconds)
  2. join(long milliseconds,long nanos)

第二个方法接受两个参数,毫秒,纳秒code

join方法是Thread类非静态方法对象

相关文章
相关标签/搜索