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

来源:互联网 发布:vmware ubuntu 全屏 编辑:程序博客网 时间:2024/04/29 12:36

等待线程终止

在有的时候,需要等待一个线程执行完后才能继续执行后面的程序;比如资源的加载,只有当加载完所有的资源后,在继续执行业务逻辑部分;那么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提供了两个方法

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

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

join方法是Thread类非静态方法


0 0
原创粉丝点击