The concept of thread can be understood as a small unit in a process. This unit is an independent execution unit, but shares the memory unit in the process with other threads in the process.
Because the CPU resources are limited, multiple threads in the process need to seize the CPU, which also leads to multiple threads in the process to execute alternately.
Thread. Sleep () indicates that the current thread is suspended for a certain period of time.
Thread. Sleep (0) The explanation on msdn is that the thread can be suspended so that other threads can wait for execution. This interpretation is easy to cause misunderstanding. We can understand that it is actually to suspend the current thread so that other threads can seize CPU resources again with the current thread.
CodeExample:
Code
Static Void Main ( String [] ARGs)
{
Console. writeline ( " Now main thread begin " );
Program P = New Program ();
Thread t = New Thread ( New Threadstart (P. threadproc ));
T. Start ();
For ( Int I = 0 ; I < 10 ; I ++ )
{
Console. writeline ( " Main thread: {0} " , I );
Thread. Sleep ( 0 ); // This only means to pause the current thread so that other threads can re-seize resources with him.
}
Console. Read ();
}
Void Threadproc ()
{
For ( Int I = 0 ; I < 10 ; I ++ )
{
Console. writeline ( " Threadproc: {0} " , I );
}
}
Execution result:
We can see that when the main thread executes a loop, sleep (0) makes the resource allocation in the two threads again. Another thread can seize the resource and execute it.
Run the following command to check the result:
We can see that when resources are re-allocated this time, the main thread grabbed the resource for execution for a period of time, followed by another thread for execution.
From the execution results, we can see that thread. Sleep (0) is the real function, and it can also be seen that threads are executed alternately.