首页 > 代码库 > 线程并发和异步

线程并发和异步

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

  

线程并发和异步