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

本文通过一个C#编程示例介绍了如何在一个程序中创建并管理多个线程,确保所有线程完成后再进行下一步操作。该示例使用了简单的死循环来检查线程状态,演示了线程启动、状态监控及同步执行的方法。

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

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 + "结束");
        }
    }
}

 

转载于:https://my.oschina.net/u/2332532/blog/1859892

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值