There are two useful functions in the Java Thread class: Sleep and yield. Sleep means the thread sleeps for a certain period of time, that is, the CPU is handed over for a period of time. yield is used to imply that the system gives control of the CPU. These two functions are particularly useful in multi-threaded development. They can allocate CPU resources reasonably and improve program running efficiency. For sleep, there is a usage that can replace yield function-sleep (0 ). Calling this function also tells the CPU to hand over control of the CPU.
In C/C ++, there are also sleep functions (sleep in windows and sleep in UNIX). You can also use sleep (0) to control the CPU.
Add this mechanism where appropriate in the Code. When the system is heavily burdened, you can balance the CPU time allocation. When the system is under low pressure, the normal operation of the program will not be affected. A simple example is to use C and Java to create two simple programs, namely group A and group B.
Group:
C ++:
# Include <windows. h>
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 <windows. h>
Void main ()
{
While (1 );
}
Java: Same as group
Run the C ++ program and Java program in group A at the same time, open the task manager, and check that the process is sorted by CPU usage time. Then, the two programs occupy the CPU, and the comparison is average, basically half.
Run C ++ and Java programs in Group B at the same time, and then check the CPU usage. This will show that most of the CPUs are occupied by C ++ programs, the CPU usage of Java programs is 0.
The above two groups of tests fully prove the role of sleep (0) and yield () Functions on CPU release. When developing a multi-task system, you may wish to consider introducing this mechanism into the program, which may receive unexpected results.