C#中关于多个线程的启动与停止

2024-11-29 01:51:05
推荐回答(2个)
回答1:

希望代码对你有帮助
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
List listThread = new List(5);

Thread thread = null;
for (int i = 0; i < 5; i++)
{
thread = new Thread(new ThreadStart(p.ThreadMethod));
thread.Name = "Thread" + (i + 1);
Console.WriteLine("创建 Thread" + (i + 1));
listThread.Add(thread);
}

//关闭指定线程
foreach (Thread tempThread in listThread)
{
if (tempThread.Name == "Thread3")
{
Console.WriteLine(tempThread.Name + " 线程已关闭");
tempThread.Abort();
}
}

Console.ReadLine();
}

private void ThreadMethod()
{

}
}
}

回答2:

StartRun方法执行结束,线程就终止
也可以使用这两个方法终止线程,
th.Abort();
th.Interrupt()
但是,你的程序中Thread ThrRun 作用域在for中,
改改...