Thread series -- thread. Sleep (0)

Source: Internet
Author: User

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.

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.