多线程学习二、初步理解代码

多线程的初步理解代码

using System;
using System.Threading;

namespace ThreadDemo
{
    class Program
    {
        //主线程
        static void Main(string[] args)
        {
            //这个是传统写法
            //ThreadStart threadStart = new ThreadStart(ThreadOne);//这句的意思是NEW一个函数给线程,也就是让线程去执行那个函数体。
            //Thread thread = new Thread(threadStart);
            //这个是语法糖简化后的写法,是编译后相当于上面那种变成new Thread(new ThreadStart(ThreadOne))
            Thread thread = new Thread(ThreadOne);
            //告诉CPU可以开始执行这个线程了,但是什么时候执行CPU说了算
            thread.Start();
            //用委托执行方法
            //委托执行还是一个主线程单线程,用Thread就是多线程
            Action action = ThreadOne;
            action();

            //匿名方法
            Thread thread1 = new Thread(delegate ()
            {
                Console.WriteLine("这是用匿名方法创建的方法");
            });
            thread1.Start();
            //用Lambda表达式创建的方法
            Thread thread2 = new Thread(() =>
            {
                Console.WriteLine("这是用匿名方法创建的方法");
            });
            thread2.Start();
            //如果在主线程直接执行这个会卡死
            //如果放在Thread执行就不会影响主线程
            Thread thread3 = new Thread(() =>
            {
                while (true)
                {
                    Console.WriteLine(DateTime.Now);
                }
            });
            thread3.Start();

            Console.ReadKey();
        }
        static void ThreadOne()
        {
            Console.WriteLine("这是个无返回值的线程");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/q1923408717/article/details/107916417