单线程与多线程

多线程的目的是是提高速度,而是同时可以执行多个功能,我觉得速度相对会变慢一些,如下小案例:

输出数字与字符串,用控制台应用程序实验:

单线程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //单线程
            Stopwatch watch = new Stopwatch();
            watch.Start();
            PrintNumb();
            PrintStr();
            watch.Stop();
            Console.WriteLine(watch.Elapsed.TotalMilliseconds);
            Console.ReadKey();
        }


        private static void PrintNumb()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine(i);
            }
        }


        private static void PrintStr()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine("您输出的是:"+i.ToString());
            }
        }
    }
}

多线程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //双线程
            ThreadStart sprintnum = new ThreadStart(PrintNumb);
            Thread tnum = new Thread(sprintnum);
            ThreadStart tprintstr = new ThreadStart(PrintStr);
            Thread tntstr = new Thread(tprintstr);


            Stopwatch watch = new Stopwatch();
            watch.Start();
            tnum.Start();
            tntstr.Start();
            while (true)
            {
                if (tnum.ThreadState==System.Threading.ThreadState.Stopped&&tntstr.ThreadState==System.Threading.ThreadState.Stopped)
                {
                    watch.Stop();
                    Console.WriteLine(watch.Elapsed.TotalMilliseconds);
                    break;
                }
            }
            Console.ReadKey();
        }


        private static void PrintNumb()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine(i);
            }
        }


        private static void PrintStr()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine("您输出的是:"+i.ToString());
            }
        }
    }
}

原文地址:https://www.cnblogs.com/duanlinlin/p/3142912.html