Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What's the point of Thread.sleep (0) in the code?

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces what is the significance of Thread.sleep (0) in the code? the content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

You think you are a senior engineer, but in fact you just know how to use a few frames of API! Recently, a Thread.sleep (0) has appeared in the code, which has attracted everyone's attention. Some people say it is wrong, others say it is meaningless and can be deleted! Is that so? Through this article, I hope you will have a greater harvest after reading it!

We know that the Thread.sleep () method can make a thread sleep for a while, but when this parameter is 0, does it make sense? Assuming that the current time is 2018-10-16 1800 Thread.sleep 00.000, will the thread that is currently dormant be awakened at 2018-10-16 18001 after I call it (0)?

To answer this question, we first need to see what Thread.sleep () has done. Since it is Sleep 0 millisecond, is it dormant after all?

We know that a processor is a tool for an operating system to execute tasks, and threads are the basic unit for an operating system to execute tasks. The number of processors determines that it is impossible for all threads to be executed at the same time. This requires some algorithm to schedule tasks. Unix system uses time slice algorithm, while Windows is a preemptive multitasking operating system.

Wikipedia has the following definition of preemptive style:

In computing, preemption is the act of temporarily interrupting a task being carried out by a computer system, without requiring its cooperation, and with the intention of resuming the task at a later time. Such a change is known as a context switch. It is normally carried out by a privileged task or part of the system known as a preemptive scheduler, which has the power to preempt, or interrupt, and later resume, other tasks in the system.

It roughly means:

Threads are scheduled to execute according to their priority. Even if the thread is executing at run time, all threads are assigned processor time slices by the operating system. The details of the scheduling algorithm used to determine the order of thread execution vary from operating system to operating system.

In some operating systems, threads with the highest priority (relative to executable threads) are always scheduled to run first. If multiple threads with the same priority are available, the scheduler traverses the threads at that priority and provides each thread with a fixed time slice (segment) to execute. As long as a thread with a higher priority can run, a thread with a lower priority will not execute. If there are no more runnable threads at the given priority, the scheduler moves to the next lower priority and dispatches the thread at that priority for execution. If a thread with a higher priority can run at this time, a thread with a lower priority is preempted and a thread with a higher priority is allowed to execute again. In addition, the operating system can dynamically adjust thread priorities when the application's user interface moves between the foreground and the background. Other operating systems can choose to use different scheduling algorithms.

Windows will not only adjust the priority when switching between the foreground and background, but also dynamically raise the priority for the Icano operation, or use the "hunger and thirst" time slice allocation strategy to dynamically adjust. If a thread has been longing for a time slice but has not obtained a time slice for a long time, Windows will temporarily raise the priority of the thread and allocate twice the time slice at a time to execute, after using up two times the time slice. The priority will be restored to the previous level.

In the time slice algorithm, all processes are queued. According to their order, the operating system allocates a period of time to each process, that is, the time that the process is allowed to run. If the process is still running at the end of the time slice, the CPU is stripped and assigned to another process. If the process blocks or ends before the end of the time slice, CPU switches immediately. All the scheduler has to do is maintain a list of ready processes, and when the process runs out of its time slice, it is moved to the end of the queue.

We use the cake-sharing scene to describe the two algorithms. Suppose there is an endless stream of cakes (endless time), a knife and fork (a CPU), and 10 people waiting to eat cake (10 processes).

If the Unix operating system is in charge of dividing the cake, then he will make this rule: everyone comes up to eat for a minute, and the time is up for the next one. When the last person finishes eating, he will start all over again. Therefore, regardless of whether the 10 people have different priorities, different degrees of hunger and different amounts of food, everyone can eat for one minute when they come up. Of course, if someone is not very hungry or eats a small amount of food and is full after 30 seconds, he can say to the operating system: I am full (hang up). So the operating system will let the next person continue.

If the Windows operating system is in charge of sharing the cake, then the scene will be very interesting. He will make a rule like this: I will give each of you a priority according to your priority and your level of hunger. The person with the highest priority can come up for cake-until you don't want to eat it. When this person has finished eating, I will re-calculate everyone's priority according to the priority and the degree of hunger, and then assign it to the person with the highest priority.

In this way, the scene is interesting. Maybe some people are beautiful MM, so they have high priority, so she can often come to eat cake. Maybe the other person is a creepy guy, so the priority is so low that it takes a long time for him to get his turn (because as time goes on, he gets hungrier and hungrier, so the total priority will be higher and higher. So one day it will be his turn). Moreover, if a fat man gets a knife and fork accidentally, because he eats a lot of food, he may occupy the cake and eat it for a long time, causing the people next to him to swallow.

What's more, it's possible that the operating system now calculates that the No. 5 beautiful MM has the highest overall priority and is much higher than others. So I called No. 5 to eat cake. The 5th ate for a while, feeling less hungry, so he said, "I won't eat" (hang up). So the operating system recalculates everyone's priorities. Because No. 5 had just eaten, her hunger became smaller, so her total priority became smaller, while others became more hungry because they waited a little longer, so the total priority became higher. At this time, however, it is still possible that No. 5 has a higher priority than the others, but now it is only a little higher than the others-but she is still the highest overall priority. So the operating system will say: No. 5 MM comes up to eat cake. (No. 5 MM is depressed, haven't you just eaten? People want to lose weight. Who told you to be so beautiful and get such a high priority.

So, what is the Thread.sleep function for?

It is also described by the scene of dividing the cake just now. In the above scene, MM No. 5 feels full after eating cake once, and she doesn't want to eat any more cake in the next half an hour, so she will tell the operating system: don't ask me to eat cake in the next half hour. In this way, when the operating system recalculates everyone's total priority in the following half an hour, it ignores MM 5. That's what the sleep function does, telling the operating system that "I won't compete in CPU for how many milliseconds in the future."

Now let's look at the question at the beginning of the article. After executing Thread.sleep (0), the current thread is not necessarily awakened, although it sleeps for 0 seconds, but after executing the sleep method, it not only hibernates, but also causes the CPU to be reassigned. Therefore, the role of Thread.Sleep (0) is to "trigger the operating system to immediately restart the CPU competition." The result of the competition may be that the current thread still takes control of CPU, or it may be replaced by another thread to gain control of CPU. This is why we often write a Thread.Sleep (0) in the big loop, because this gives other threads the right to gain control of the CPU, so that some functions do not pretend to die there.

Finally, although it is mentioned above that "unless it gives up using CPU, it will completely occupy CPU", this behavior is still restricted-the operating system will monitor your occupation of CPU, and if you find that a thread has occupied CPU for a long time, it will force the thread to hang, so in fact, there will not be a situation where "a thread has been occupying CPU all the time". As for our big loop causing the program to fake death, it is not because this thread has been occupying the CPU. In fact, the operating system has competed for CPU many times during this period of time, but other threads quit shortly after gaining control of CPU, so it was this thread's turn to continue to execute the loop, so it took a long time to be forced to suspend by the operating system. So when it comes to the program, it looks as if the thread has been occupying CPU.

What is the significance of Thread.sleep (0) in the code? so much for sharing here. I hope the above content can be helpful to everyone and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report