默认的优先级
Thread 中默认定义了三种优先级: MIN_PRIORITY, NORM_PRIORITY,MAX_PRIORITY。
以下为源码
/**
* The minimum priority that a thread can have.
*/
public static final int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public static final int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public static final int MAX_PRIORITY = 10;
在Java中线程的优先级分为 10 个等级,即 1~10,通过源码可以看到,如果小于 1 或大于 10,该方法将抛出异常 throw new IllegalArgumentException()。
可以通过以下的方法设置。
public final void setPriority(int newPriority)
演示代码如下:
System.out.println("main 线程的优先级: " + Thread.currentThread().getPriority());
System.out.println("设置 main 线程的优先级设置为 7");
Thread.currentThread().setPriority(7);
System.out.println("main 线程的优先级: " + Thread.currentThread().getPriority());
线程优先级具有继承特性
在 Java 中, 优先级在线程的启动运行中将被继承,比如 Thread A 线程启动 Thread B 线程,则 Thread B 线程的优先级与 Thread A 是一样的。根据个人的使用和测试,想要继承线程的优先级,必须在创建阶段(New)前就设置优先级,否则就无法继承优先级了。
优先级并不绝对
虽然线程可以设置优先级,但是这个优先级并不是绝对的优先。在运行中只是 CPU 会尽量记住是尽量将执行的资源优先给优先级别比较高的线程。
优先级别比较高的可能会优先执行,或者大部分能先执行。多执行几遍,看到的效果是不一样的. 这里不能把运行结果的顺序和线程的优先级作为比较, 优先级别比较高,但是不代表都最先执行完,这些都是不确定以及随机性的。看 CPU 怎么分配了。