Java并发编程实例--6.线程的join方法
有时我们需要等到某个线程执行完毕。例如,我可能有一个线程来初始化资源完毕然后其他线程才能开始执行。
谓词,我们可以使用Thread类的join()方法。
谓词,我们可以使用Thread类的join()方法。
本例中,我们将学习使用这个方法。
DataSourcesLoader.java
package com.dylan.thread.ch1.c06;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @author xusucheng
* @create 2018-04-25
**/
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());
}
}
NetworkConnectionsLoader.java
package com.dylan.thread.ch1.c06;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @author xusucheng
* @create 2018-04-25
**/
public class NetworkConnectionsLoader implements Runnable {
@Override
public void run() {
// Writes a message
System.out.printf("Begining network connections loading: %s\n",new Date());
// Sleep six seconds
try {
TimeUnit.SECONDS.sleep(6);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Writes a message
System.out.printf("Network connections loading has finished: %s\n",new Date());
}
}
Main.java
package com.dylan.thread.ch1.c06;
import java.util.Date;
/**
* @author xusucheng
* @create 2018-04-25
**/
public class Main {
public static void main(String[] args) {
DataSourcesLoader dsLoader = new DataSourcesLoader();
Thread thread1 = new Thread(dsLoader,"DataSourceThread");
NetworkConnectionsLoader ncLoader = new NetworkConnectionsLoader();
Thread thread2 = new Thread(ncLoader,"NetworkConnectionLoader");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("Main: Configuration has been loaded: %s\n",new Date());
}
}
输出:
Beginning data sources loading: Wed Apr 25 23:11:50 CST 2018
Begining network connections loading: Wed Apr 25 23:11:50 CST 2018
Data sources loading has finished: Wed Apr 25 23:11:54 CST 2018
Network connections loading has finished: Wed Apr 25 23:11:56 CST 2018
Main: Configuration has been loaded: Wed Apr 25 23:11:56 CST 2018