多線程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 + "結束");
        }
    }
}
相關文章
相關標籤/搜索