打赏

Thread.Sleep会让出cpu,证明如下

using System;
using System.Threading;

namespace Test
{
    class Program
    {
        public static void CallToChildThread()
        {
            Console.WriteLine("ThreadId:" + Thread.CurrentThread.ManagedThreadId);
            //Thread.Sleep(200000); 

            while (true)
            {

            }
        }

        public static void CreatThread()
        {
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Thread childThread = new Thread(childref);
            childThread.Start();
        }

        public static void Run()
        {
            for (int i = 0; i < 100000; i++)
            {
                Console.WriteLine("Run:" + i);
            }
        }

        public static void CreatRun()
        {
            ThreadStart childref = new ThreadStart(Run);
            Thread childThread = new Thread(childref);
            childThread.Start();
        }

        static void Main(string[] args)
        {
            for (int i = 0; i < 50; i++)
            {
                CreatThread();
            }

            for (int i = 0; i < 10; i++)
            {
                CreatRun();
            }



            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }
    }
}

  

一:CallToChildThread死循环时,新创建线程很慢,重点是没有RunData,执行效果如下图:
public static void CallToChildThread()
        {
            Console.WriteLine("ThreadId:" + Thread.CurrentThread.ManagedThreadId);
            //Thread.Sleep(200000); 

            while (true)
            {

            }
        }

 

二.CallToChildThread   Thread.Sleep(200000);时,瞬间完成新创建线程,RunData立马执行,且打印值,,执行效果如下图:

public static void CallToChildThread()
        {
            Console.WriteLine("ThreadId:" + Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(200000);

            //while (true)
            //{

            //}
        }

  

 

posted @ 2021-04-01 20:55  刘奇云  阅读(780)  评论(0编辑  收藏  举报