Thread对象.Join()的官方含义:
在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程,直到某个线程终止为止。
简言之,当调用thread.Join();后面的线程将停止执行,直到与thread对应的函数逻辑执行完毕,方可执行thread.Join()下面的代码。
示例代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StudyDemo
{
class Program
{
static void Main(string[] args)
{
double carFee = 36.32 + 14.3 + 50.32;
Thread th = new Thread(() => GetFunc());
Console.WriteLine("线程状态1:" + th.ThreadState);
th.IsBackground = true;
Console.WriteLine("线程状态2:" + th.ThreadState);
th.Start();
Console.WriteLine("线程状态3:" + th.ThreadState);
//Join的意思是 确保线程th执行完毕后,方可执行th.Join()下面的代码
th.Join();
Console.WriteLine("线程状态4:" + th.ThreadState);
Console.WriteLine("车船费:{0}", carFee);
Console.WriteLine("市内交通费:{0}", 459.92 - carFee + 33.9);
Console.WriteLine("线程状态5:" + th.ThreadState);
Console.ReadLine();
}
/// <summary>
/// 线程函数
/// </summary>
static void GetFunc()
{
for (int i = 0; i < 3; i++)
{
Thread.Sleep(new Random().Next(1000, 1200));
Console.WriteLine("Func" + (i + 1));
}
}
}
}
执行效果如图: