如何判断线程已经结束
假定现在有一个循环,里面开启了10个线程。
循环里面包含如下两行代码:
Thred t = new Thread(Run);
t.Start();
怎么判断这10个线程都跑完了,其中的资源都释放完毕了?
[解决办法]
private static AutoResetEvent[] autoEvents = new AutoResetEvent[10];
public static void Run()
{
int index = int.Parse(Thread.CurrentThread.Name);
Console.WriteLine(string.Format("当前时间{0},当前线程{1}", DateTime.Now, index));
autoEvents[index].Set(); <---这里
}
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
autoEvents[i] = new AutoResetEvent(false);
Thread t = new Thread(new ThreadStart(Run));
t.Name = i.ToString();
t.Start();
}
WaitHandle.WaitAll(autoEvents); <---这里
Console.WriteLine("所有线程都结束完毕");
Console.ReadKey();
}