线程Thread中 Thread.Join() 方法的解释
今天是第一次在C#中接触Thread,自己研究了一下其中Thread.Join()这个方法,下面谈谈自己的理解。
Thread.Join()在MSDN中的解释很模糊:Blocks the calling thread until a thread terminates
有两个主要问题:1.什么是the calling thread?
2.什么是a thread?
首先来看一下有关的概念: 我们执行一个.exe文件实际上就是开启了一个进程,同时开启了至少一个线程,
但是真正干活的是线程,就好比一个Team有好几个人,但是真正干活的是人不是Team.
具体到代码来说,以Console Application为例:程序Test.exe从Main函数开始运行,实际上是有一个线程
在执行Main函数,我们称作MainThread.假如我们在Main函数中声明了一个Thread,称作NewThread,并且调用了
NewThread.Start()的方法,那么 MainThread在处理Main函数里面的代码时遇到NewThread.Start()时,就会
去调用NewThread.
基于上面的讨论,我们可以得出结论:在我们刚才的例子中the calling thread就是MainThread,而a thread
指的洽洽就是MainThread调用的NewThread线程。
现在回到MSDN的解释,我们可以这么翻译:当NewThread调用Join方法的时候,MainThread就被停止执行,
直到NewThread线程执行完毕。这样就好理解了吧O(∩_∩)O哈哈~
using System.Threading; namespace chapter12_join1 { class Program { static void Main( string [] args) { Thread.CurrentThread.Name = "MainThread" ; Thread newThread = new Thread( new ThreadStart(ThreadFuncOne)); newThread.Name = "NewThread" ; for ( int j = 0; j < 100; j++) { if (j == 30) { newThread.Start(); newThread.Join(); } else { Console.WriteLine(Thread.CurrentThread.Name + " j = " + j); } } Console.Read(); } private static void ThreadFuncOne() { for ( int i = 0; i < 100; i++) { Console.WriteLine(Thread.CurrentThread.Name + " i = " + i); } Console.WriteLine(Thread.CurrentThread.Name + " has finished" ); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace chapter12_join1 { class Program { static void Main( string [] args) { Thread.CurrentThread.Name = "MainThread" ; Thread newThread = new Thread( new ThreadStart(ThreadFuncOne)); newThread.Name = "NewThread" ; for ( int j = 0; j < 10; j++) { if (j == 5) { newThread.Start(); newThread.Join(1); } else { Console.WriteLine(Thread.CurrentThread.Name + " j = " + j); } } Console.Read(); } private static void ThreadFuncOne() { for ( int i = 0; i < 30; i++) { Console.WriteLine(Thread.CurrentThread.Name + " i = " + i); } Console.WriteLine(Thread.CurrentThread.Name + " has finished" ); } } } |
如果吧代码中得Join() 改为Join(1),那么就是,把newThread合并到到MainThread中1毫秒的时间,如果1毫秒的时间内没有结束,就在MainThread中释放newThread进程。
此时,结果如图
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· DeepSeek+PageAssist实现本地大模型联网
· 手把手教你更优雅的享受 DeepSeek
· Java轻量级代码工程
· 从 14 秒到 1 秒:MySQL DDL 性能优化实战