多线程Thread-多线程顺序执行

需求:如今有两个任务,任务1和任务2,任务1中有多个线程,而且任务2必须等任务1完成后才能执行。spa

namespace TThread
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 100;
            TheadInfo[] threadInfos = new TheadInfo[num];
            for(int i = 0; i< num; i++)
            {
                TheadInfo theadInfo = new TheadInfo();
                theadInfo.ThreadName = "Thread" + i;
                theadInfo.ThreadStatus = '0';
                threadInfos[i] = theadInfo;
            }
            for(int i = 0; i < num; i++)
            {
                TMyThread myThread = new TMyThread();
                myThread.theadInfo = threadInfos[i];
                Thread thd = new Thread(myThread.DoWork);
                thd.Start();
            }
            bool hasFinished = true;
            //增长死循环,判断线程是否所有结束
            while (true)
            {
                hasFinished = true;
                Thread.Sleep(1000);  //暂停1s钟,让配对的线程有匹配的机会
                foreach (TheadInfo item in threadInfos)
                {
                    Console.WriteLine(item.ThreadName+"  "+item.ThreadStatus);
                    if (item.ThreadStatus == '0')
                    {
                        hasFinished = false;
                        break;
                    }
                }
                if (hasFinished)
                    break;
            }
            Console.WriteLine("All Threads Finished");
            Console.ReadKey();
        }
    }

    class TheadInfo
    {
        public string ThreadName;
        public char ThreadStatus;
    }
    class TMyThread
    {
        public TheadInfo theadInfo;     
        public void DoWork()
        {
            Console.WriteLine("线程 "+ theadInfo.ThreadName + "开始");
            Thread.Sleep(500);
            theadInfo.ThreadStatus = '1';
            Console.WriteLine("线程 " + theadInfo.ThreadName + "结束");
        }
    }
}
相关文章
相关标签/搜索