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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构