日期:2014-05-18  浏览次数:20862 次

程序线程问题!如何等到所有的线程结束然后才执行我的代码
using   System;
using   System.Threading;
using   System.Data;
using   System.Data.SqlClient;
namespace   ThreadEx
{
class   A
{
int   start;
int   end;
public   A(int   start,int   end)
{
this.start=start;
this.end=end;
}
public   A(string   start,string   end)
{
this.start=int.Parse(start);
this.end=int.Parse(end);
}

public   void   Fun()
{

for(int   i=this.start;i <end;i++)
{
Console.WriteLine( "当前{0}线程执行了:{1} ",Thread.CurrentThread.Name,i.ToString());
}

}
}

///   <summary>
///   Class1   的摘要说明。
///   </summary>
class   Class1
{

private   static   bool   IsCloseAllThread(Thread[]   tr)
{
for(int   i=0;i <tr.Length;i++)
{
if(tr[i].IsAlive)
{
return   false;
}
}
return   true;
}
///   <summary>
///   应用程序的主入口点。
///   </summary>
[STAThread]
public   static   void   Main(string[]   args)
{
//
//   TODO:   在此处添加代码以启动应用程序
//

System.Collections.Hashtable   hs=new   System.Collections.Hashtable();
Thread[]   tr=new   Thread[4];
A[]   a=new   A[tr.Length];
int   count=50;//记录总数
int   threads=tr.Length;//线程总数
int   step=count/threads;//步长,每次循环之间的基数
int   residue=count%threads;//数据中的余数  

//计算每次循环之间的步长
for(int   i=0;i <count;i+=step)
{
//如果有余数并且已经到了   临界点:例如   10/3   临界点是9
if(residue!=0   &&   i+step==count-residue)
{
hs[i.ToString()]=i+step+residue;
break;
}
else
{
hs[i.ToString()]=i+step;
}
}
int   tempI=0;


foreach(string   k   in   hs.Keys   )
{
if(tempI <a.Length)
{
a[tempI]=new   A(k.ToString(),hs[k].ToString());//初始化数组中的A对象
tr[tempI]=new   Thread(new   ThreadStart(a[tempI].Fun));//不同的线程对应不同的A对象
tr[tempI].Name= "TreadClass1_ "+tempI.ToString();//设置线程的名字
tr[tempI].Start();
tempI++;
}
}

// for(int   i=0;i <a.Length;i++)
// {
// tr[i].Start();//启动线程
//// Console.WriteLine(k.ToString()+ ", "+hs[k].ToString());
// }

Console.WriteLine(Thread.CurrentThread.Name+ ":AAAAAAAAAAAAAAAAAAAAAAAAAAAA ");

}
}
}


我的程序执行的时候为什么会先打印AAAAAAAAAAAAAAAAAAAAAAAAAAAA,也就是  
当我Console.WriteLine(Thread.CurrentThread.Name+ ":AAAAAAAAAAAAAAAAAAAAAAAAAAAA ");这段代码的时候   ,第一个线程已经开始执行了
我想等到所有的   线程都停掉然后在执行我的
Console.WriteLine(Thread.CurrentThread.Name+ ":AAAAAAAAAAAAAAAAAAAAAAAAAAAA ");这段

------解决方案--------------------
写一个循环检查一下是不是tr中的所有线程的状态都是ThreadState.Stopped。如果有一个不是ThreadState.Stopped状态则继续等待,如果都已完成,则向下执行,比如:

while (true)
{
bool stop = true;
foreach (Thread t in tr)
{
if (t.ThreadState != ThreadState.Stopped)
{
stop = false