static void Main()
{
Console.WriteLine("开始");
#region -- 多线程测试实例 关键字:Thread(using System.Threading)
//无参数的委托 (textFunction:无参数的方法 textFunction())
Thread thread = new Thread(new ThreadStart(TextFunction));
//开启线程
thread.Start();
//有参数的委托(textFunction:有参数的方法 textFunction(Object test))
//注:如需要使用ParameterizedThreadStart ,则必须使用输入参数为Object的方法
Thread thread1 = new Thread(new ParameterizedThreadStart(TextFunction));
//开启线程并给方法赋入输入参数
thread1.Start(20);
//将当前线程挂起指定的毫秒数
Thread.Sleep(1000);
//阻止调用线程,直到某个线程终止或者时间经过了指定的毫秒数
thread1.Join(1000);//单位:毫秒
thread1.Join(TimeSpan.FromSeconds(2));
//阻止调用线程,直到上一个线程终止
thread1.Join();//单位:秒
//终止线程
thread1.Abort();
#endregion
Console.WriteLine("结束");
Console.ReadLine();
}
/// <summary>
/// 无参数的方法
/// </summary>
public static void TextFunction()
{
Console.WriteLine("---------------- 第一个线程开始-----------------");
for (int i=0;i<10000;i++)
{
Console.WriteLine();
}
Console.WriteLine("---------------- 第一个线程结束-----------------");
Console.WriteLine();
}
/// <summary>
/// 有参数的方法
/// </summary>
/// <param name="test"></param>
public static void TextFunction(object test)
{
Console.WriteLine();
Console.WriteLine("---------------- 第二个线程开始-----------------");
for (int i = 0; i < test.ToString().ParseInt().GetValueOrDefault(); i++)
{
//将线程挂起指定的毫秒数
Thread.Sleep(1000);
Console.WriteLine($"**************** 第二个线程第 {i} 条数据******************");
}
Console.WriteLine("---------------- 第二个线程结束-----------------");
}