Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top