The standard advice given about using Java thread priorities can be found on p.218 in Java Concurrency In Practice:
Avoid the temptation to use thread priorities, since they increase platform dependence and can cause liveness problems. Most concurrent applications can use the default priority for all threads.
But when was the last time good advice prevented us from having a little fun?
Q: What will the following Java program print?
public class Foo {
public static void main(String[] args) throws Exception {
MyThread[] ts = new MyThread[] {new MyThread(), new MyThread()};
ts[0].setPriority(Thread.MAX_PRIORITY);
ts[1].setPriority(Thread.MIN_PRIORITY);
for (Thread t: ts) t.start();
Thread.sleep(1000);
synchronized(MyThread.class) {
MyThread.done = true;
}
for (Thread t: ts) t.join();
System.out.println(ts[0].counter > ts[1].counter);
}
}
class MyThread extends Thread {
public static boolean done = false;
public int counter = 0;
public void run() {
while (true) synchronized(MyThread.class) {
if (done) return;
counter++;
}
}
}