Thread priorities
In this chapter you will learn:
Control Thread priorities
Thread priorities are used by the thread scheduler to decide
when each thread should be allowed to run.
To set a thread's priority, use the setPriority()
method,
which is a member of Thread
.
This is its general form:
final void setPriority(int level)
The value of level must be within the range MIN_PRIORITY
and
MAX_PRIORITY
.
To return a thread to default priority, specify NORM_PRIORITY
.
These priorities are defined as static final variables within Thread.
You can obtain the current priority setting by calling the
getPriority()
method of Thread
, shown here:
final int getPriority()
The following example demonstrates two threads at different priorities.
One thread is set two levels above the
normal priority, as defined by Thread.NORM_PRIORITY
,
and the other is set to two levels below it.
The threads are started and allowed to run for ten seconds. Each thread executes a loop, counting the number of iterations. After ten seconds, the main thread stops both threads. The number of times that each thread made it through the loop is then displayed.
class MyThread implements Runnable {
long click = 0;
Thread t;// j a v a 2 s . co m
private boolean running = true;
public MyThread(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}
public class Main {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
MyThread hi = new MyThread(Thread.NORM_PRIORITY + 4);
MyThread lo = new MyThread(Thread.NORM_PRIORITY - 4);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
The code above generates the following result.
Thread.MIN_PRIORITY vs Thread.MAX_PRIORITY
The following code uses the predefined constant value
Thread.MIN_PRIORITY
vs Thread.MAX_PRIORITY
to set the minimum and maximum priority for threads.
public class Main {
/*j a v a 2 s . c om*/
public static void main(String[] args) {
Runnable runner = new MyRunnable("First");
Thread t = new Thread(runner);
t.setPriority(Thread.MIN_PRIORITY);
t.start();
runner = new MyRunnable("Second");
t = new Thread(runner);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
}
class MyRunnable implements Runnable {
protected String name;
public MyRunnable(String tn) {
name = tn;
}
public void run() {
while (true) {
System.out.println(name);
}
}
}
Next chapter...
What you will learn in the next chapter: