C# Thrad学习 第一节 Join函数
Join 当前调用者自己的方法先执行,
static Thread th1, th2;
static void Main(string[] args)
{
th1 = new Thread(ThreadFun1);
th1.Name = "线程壹";
th1.IsBackground = true;
th1.Start();
th2 = new Thread(ThreadFun2);
th2.Name = "线程贰";
th2.IsBackground = true;
th2.Start();
Console.Read();
}
static void ThreadFun1()
{
th2.Join();
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"当前运行的线程:{Thread.CurrentThread.Name},打印数据:{i}");
}
}
static void ThreadFun2()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"当前运行的线程:{Thread.CurrentThread.Name},打印数据:{i}");
}
}
执行结果
当前运行的线程:线程贰,打印数据:0
当前运行的线程:线程贰,打印数据:1
当前运行的线程:线程贰,打印数据:2
当前运行的线程:线程贰,打印数据:3
当前运行的线程:线程贰,打印数据:4
当前运行的线程:线程壹,打印数据:0
当前运行的线程:线程壹,打印数据:1
当前运行的线程:线程壹,打印数据:2
当前运行的线程:线程壹,打印数据:3
当前运行的线程:线程壹,打印数据:4
static void ThreadFun1()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"当前运行的线程:{Thread.CurrentThread.Name},打印数据:{i}");
//在这里调用 更明显
th2.Join();
}
}
当前运行的线程:线程壹,打印数据:0
当前运行的线程:线程贰,打印数据:0
当前运行的线程:线程贰,打印数据:1
当前运行的线程:线程贰,打印数据:2
当前运行的线程:线程贰,打印数据:3
当前运行的线程:线程贰,打印数据:4
当前运行的线程:线程壹,打印数据:1
当前运行的线程:线程壹,打印数据:2
当前运行的线程:线程壹,打印数据:3
当前运行的线程:线程壹,打印数据:4