Thread Priorities


Threads can specify different priority levels. The scheduler uses a thread's priority as a suggestion for how often the thread should get attention. The main thread that executes has a default priority assigned to it, THRead.NORM_PRIORITY. A priority is an integer, bounded by Thread.MIN_PRIORITY on the low end and Thread.MAX_PRIORITY on the high end.

You might use a lower priority for a thread that executes in the background. In contrast, you might use a higher priority for user interface code that needs to be extremely responsive. Generally, you will want to deviate from NORM_PRIORITY only by small amounts, such as +1 and -1. Deviating by large amounts can create applications that perform poorly, with some threads dominating and others starving for attention.

Every thread (other than the main thread) starts with the same priority as the thread that spawned it. You can send a thread the message setPriority to specify a different priority.

The following snippet of code from the Clock class shows how you might set the priority for the clock to a slightly lower value.

 public void run() {    Thread.currentThread().setPriority(Thread.NORM_PRIORITY - 1);    long lastTime = System.currentTimeMillis();    while (run) {       try {Thread.sleep(10); }       catch (InterruptedException e) {}       long now = System.currentTimeMillis();       if ((now / 1000) - (lastTime / 1000) >= 1) {          listener.update(new Date(now));          lastTime = now;       }    } } 

Note use of the currentThread static method, which you can always call to obtain the Thread object that represents the thread that is currently executing.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net