本文是学习网络上的文章时的总结,感谢大家无私的分享。
1、在某些情况下,我们需要等待线程的终结。例如,我们可能会遇到程序在执行前需要初始化资源。在执行剩下的代码之前,我们需要等待线程完成初始化任务。为了达到此目的,我们使用Thread类的join()方法。当前线程调用某个线程的这个方法时,它会暂停当前线程,直到被调用线程执行完成。
2、Java提供2种形式的join()方法:
Join(longmilliseconds)
Join(long milliseconds,long nanos)
第一种join方法,让调用线程等待特定的毫秒数。例如,如果thread1对象使用代码thread2.join(1000),那么线程thread1暂停运行,直到
以下其中一个条件发生:
Thread2结束运行
1000毫秒过去了
当其中一个条件为真时,join()方法返回。
第二个版本的join方法和第一个很像,只不过它接收一个毫秒数和一个纳秒数作为参数。
举例
package chapter; import java.util.Date; import java.util.concurrent.TimeUnit; public class DataSourcesLoader implements Runnable{ @Override public void run() { System.out.printf("Beginning data sources loading : %s\n", new Date()); try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Data sources loading has finished :%s\n",new Date()); } }
package chapter; import java.util.Date; import java.util.concurrent.TimeUnit; public class NetwworkConnectionsLoader implements Runnable{ @Override public void run() { System.out.printf("Beginning Net sources loading : %s\n", new Date()); try { TimeUnit.SECONDS.sleep(6); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Net sources loading has finished :%s\n",new Date()); } }
package chapter; import java.util.Date; public class Main6 { /** * <p> * </p> * @author zhangjunshuai * @date 2014-8-14 下午4:40:58 * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { DataSourcesLoader dsLoader = new DataSourcesLoader(); Thread thread1 = new Thread(dsLoader,"DataSourcesLoader" + ""); NetwworkConnectionsLoader ncLoader = new NetwworkConnectionsLoader(); Thread thread2 = new Thread(ncLoader,"NetwworkConnectionsLoader"); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.printf("Main: Configuration has been loaded: %s\n",new Date()); } }
运行结果
以上为书本示例,我在网上找了一个示例。
package mytest; class Thread1 extends Thread { public Thread1(String threadName) { super(threadName); } public void run() { System.out.println(getName() + "is running"); try { sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread1 is over"); } }
package mytest; class Thread2 extends Thread { private Thread1 thread1; public Thread2(String threadName, Thread1 thread1) { super(threadName); this.thread1 = thread1; } public void run() { System.out.println(getName() + "is running"); try { thread1.start(); thread1.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread2 is over"); } }
package mytest; public class JoinTest { public static void main(String[] args) { Thread1 thread1 = new Thread1("Thread1"); Thread2 thread2 = new Thread2("Thread2", thread1); thread2.start(); } }
运行结果
如果去除join方法
Java并发学习之六——等待线程的终结
时间: 2024-10-15 17:49:59