线程并发和异步

    class Program
    {
        //主线程
        static void Main(string[] args)
        {
            StartThreads();

            Console.ReadKey();
        }

        public static void StartThreads()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            Thread t1 = new Thread(Print1);
            t1.Name = "Thread1";
            Thread t2 = new Thread(Print1);
            t2.Name = "Thread2";
            Thread t3 = new Thread(Print1);
            t3.Name = "Thread3";

            //启动3个新的线程(同时执行Print1操作,属于并发行为)
            t1.Start();
            t2.Start();
            t3.Start();

            //注释掉线程Join方法,对主线程的后续程序来说存在异步行为
            //t1.Join();
            //t2.Join();
            //t3.Join();
            Console.Write(watch.Elapsed);

            watch.Restart();
            Print2();
            Console.Write(watch.Elapsed);
        }

        public static void Print1()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine(Thread.CurrentThread.Name+":"+i);
            }
        }

        public static void Print2()
        {
            for (int i = 0; i < 3000; i++)
            {
                Console.WriteLine(i);
            }
        }
    }

  

转载于:https://www.cnblogs.com/Arlar/p/6068725.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值