C and Java Sleep and Yield

xiaoxiao2021-03-06  76

There are two useful functions in the Java's Thread class, Sleep and Yield, Sleep is a certain time of thread sleep, that is, the CPU is handed over, and Yield is used to hint the system to hand over the CPU control. These two functions are particularly useful when multi-threaded development, which can be assigned a CPU to improve the running efficiency of the program. For Sleep, there is a usage that can replace the Yield function - Sleep (0). Calling this function is also equivalent to telling the CPU to hand over the control of the CPU. In C / C , there is also a SLEEP function (Windows called Sleep, Unix snleep), and you can also use Sleep (0) usage to hand over the control of the CPU. This mechanism is added in the appropriate place in the code. When the system burden is more important, the allocated CPU time can be balanced, and when the system is small, it does not affect the normal operation of the program. To give a simple example, two sets of simple procedures are used in C and Java, divided into group A and Group B. Group A: C : #include void main () {while (1) Sleep (0);} java: public class mythread extends thread {public static void main (string [] args) throws exception {system. Out.println ("Start Runing ..."); while (true) {yield;}} Group B: C : #include void main () {while (1);} java: The same simultaneously run the C program with the Java program, then open the task manager, and view the process Posing the time sort by the CPU, it will find that the two programs occupy the CPU, and more average, basically half half. At the same time, run the C program with the Java program in group B, and then view the CPU usage, it will find that most of the CPUs are occupied by C programs, while the CPU usage of the Java program is 0. The above two sets of tests fully demonstrate the role of the SLEEP (0) and Yield () functions to release the CPU. When you develop multi-task systems, you may wish to consider this mechanism in the program, perhaps you can receive unexpected effects.

转载请注明原文地址:https://www.9cbs.com/read-92857.html

New Post(0)