码迷,mamicode.com
首页 > 编程语言 > 详细

线程并发和异步

时间:2016-11-16 15:02:59      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:存在   for   div   res   ring   ram   thread   rest   ons   

    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);
            }
        }
    }

  

线程并发和异步

标签:存在   for   div   res   ring   ram   thread   rest   ons   

原文地址:http://www.cnblogs.com/Arlar/p/6068725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!