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)