线程等待,或者说叫等待线程。其语句是 线程名.Join() 。按照我的理解,这个语句其实是告诉系统程序,这个线程很重要,你必须使用全部的计算资源供他计算,等他计算结束了之后再回到这个位置。
举例来说,下面这个程序就用了线程等待的技术,t.Join()使得cpu先执行完了t线程内的计算然后再继续主函数的运算。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using static System.Console;
namespace Ch01Re03
{
class Program
{
static void Main(string[] args)
{
WriteLine("Starting...");
Thread t = new Thread(PrintNumbersWithDelay);
t.Start();
t.Join();
WriteLine("Thread ends...");
ReadKey();
}
static void PrintNumbersWithDelay()
{
WriteLine("Thread starting...");
for (int i=0;i<10;i++)
{
Thread.Sleep(TimeSpan.FromSeconds(2));
WriteLine(i);
}
}
}
}
当主线程执行到t.Jooin()一句时,跳转到t线程并等待t线程执行完成后再跳转回主线程继续执行