C#:线程(2):创建线程

一:创建新线程

在C#里,线程是一种已经定义好的类,其被定义在System.Threading命名空间内,因此创建新线程和我们实例化对象并没有本质的差别。在这里,用一个最简单的例子说明如何创建新线程。

(一):创建新的控制台程序,在控制台程序的主函数下面,写一个希望在新线程中调用的函数

static void OutPut()
        {
            for (int i=0;i<10;i++)
            {
                Console.WriteLine(i);
            }
        }

该函数的作用就是在控制台输出从0到9的数

(二):在主函数中实例化新的线程然后运行,在主函数中输入

static void Main(string[] args)
        {
            System.Threading.Thread t = new System.Threading.Thread(OutPut);
            t.Start();

            Console.ReadKey();
        }

运行得到

(三):对代码的讲解

System.Threading.Thread t = new System.Threading.Thread(OutPut);

创建线程对象t,每当t运行,启动函数OutPut

t.Start();

启动线程t

猜你喜欢

转载自blog.csdn.net/buaazyp/article/details/81015483