有时我们需要等到某个线程执行完毕。例如,我可能有一个线程来初始化资源完毕然后其他线程才能开始执行。
谓词,我们可以使用Thread类的join()方法。
谓词,我们可以使用Thread类的join()方法。
本例中,我们将学习使用这个方法。
DataSourcesLoader.javapackage 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.javapackage 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.javapackage 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

本文通过两个具体的例子,展示了如何使用Java中的Thread类的join()方法实现线程间的同步。首先介绍了数据源加载和网络连接加载两个任务,并通过主线程等待这两个任务完成后再继续执行的方式,确保了资源初始化完毕后才开始其他操作。

被折叠的 条评论
为什么被折叠?



