Thread series--thread.sleep (0)

Source: Internet
Author: User

Because CPU resources are limited, multiple threads in a process want to preempt the CPU, which also causes multiple threads in the process to execute alternately.

Thread.Sleep () itself means that the current thread hangs for a certain amount of time.

Thread.Sleep (0) The explanation on MSDN is that suspending this thread enables other waiting threads to execute. This explanation is prone to misunderstanding, and we can understand that the current thread is suspended, allowing other threads to preempt CPU resources again with the current thread.

code example:

1 Code2 3  Static voidMain (string[] args)4         {5Console.WriteLine ("Now main thread begin");6Program p=NewProgram ();7Thread T =NewThread (NewThreadStart (P.threadproc));8 T.start ();9              for(inti =0; I <Ten; i++)Ten             { OneConsole.WriteLine ("Main thread:{0}", i); AThread.Sleep (0);//This simply means that the current thread is paused, causing the other threads to re-preempt the resource again . -             } - Console.read (); the         } -        voidThreadProc () -         { -              for(inti =0; I <Ten; i++) +             { -Console.WriteLine ("threadproc:{0}", i); +             } A}

Execution Result:

You can see that when the main thread executes a loop, Sleep (0) makes the resource re-allocated in two threads. Another thread is preempted to the resource and executes.

Take a second and look at the results:

You can see that this time the reallocation of resources, first the main thread to the resource execution for a period of time, followed by another thread execution.

From the implementation results can be seen, Thread.Sleep (0) of the real role, but also can be seen between multithreading is alternately executed.

Thread series--thread.sleep (0)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.