优先级高的线程在竞争资源时会更有优势,更可能抢占资源,只是一个概率问题;
线程的优先级调度和底层操作系统有密切的关系,在各个平台上表现不一,并且无法精准控制,因此在要求严格的场合,需要开发者在应用层解决线程调度问题;
线程优先级用内置3个静态标量表示:
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;
虽然设置最高和最低优先级,但真正执行结果不可预测:
public class ThreadPriorityDemo {
public static class HighPriorityThread extends Thread {
static int count = 0;
@Override
public void run() {
while (true) {
synchronized (ThreadPriorityDemo.class) {
count++;
if (count > 10000000) {
System.out.println("HighPriorityThread is complete." + System.currentTimeMillis());
break;
}
}
}
}
}
public static class LowPriorityThread extends Thread {
static int count = 0;
@Override
public void run() {
while (true) {
synchronized (ThreadPriorityDemo.class) {
count++;
if (count > 10000000) {
System.out.println("LowPriorityThread is complete." + System.currentTimeMillis());
break;
}
}
}
}
}
public static void main(String[] args) {
Thread high = new HighPriorityThread();
Thread low = new LowPriorityThread();
high.setPriority(Thread.MAX_PRIORITY);
low.setPriority(Thread.MIN_PRIORITY);
System.out.println("start:" + System.currentTimeMillis());
high.start();
low.start();
}
}
console
start:1549722133524
LowPriorityThread is complete.1549722134435
HighPriorityThread is complete.1549722134440