Why is the thread priority set to maximum in a loop in this java applet tutorial code?

旧时模样 提交于 2019-12-13 04:00:00

问题


I'm trying to learn some basic java programming for games.

I'm following this tutorial here.

Their skeleton code for the run method in an applet:

public void run () 
{
    // lower ThreadPriority 
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY); 

    // run a long while (true) this means in our case "always" 
    while (true) 
    {
        // repaint the applet 
        repaint(); 

        try 
        {
            // Stop thread for 20 milliseconds 
            Thread.sleep (20); 
        } 
        catch (InterruptedException ex) 
        {
            // do nothing 
        } 

        // set ThreadPriority to maximum value 
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY); 
    }
}

In this code they initially set the thread priority to minimum. Then inside the loop they set it to maximum.

I was wondering what the purpose of this is?


回答1:


I don't know why they decided to set the priority to minimum initially. I think this is pointless.

However, setting the priority to higher than normal (maybe maximum is an exaggeration) does make sense.

In general, if you have a thread that repeatedly performs a short action then sleeps, what you generally want is to try and maximise the probability of the thread "kicking in on time, doing its thing, then going back to sleep" on each iteration. Broadly speaking, setting the thread priority to higher than average increases the chance of this happening. This is particularly true on Windows, where thread priority essentially affects what thread gets scheduled in at the points where the thread scheduler is deciding "what to run next".

You might want to read through an article I wrote a couple of years ago on Java thread priority that may help to explain some of the issues involved.



来源:https://stackoverflow.com/questions/10464230/why-is-the-thread-priority-set-to-maximum-in-a-loop-in-this-java-applet-tutorial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!