线程的优先级告诉程序该线程的重要程度有多大。 如果有大量程序都被堵塞, 都在等候运行, 程序会尽可能地运行优先级的那个程序。 但是, 这并不表示优先级较低的线程不会运行。 若程序的优先级较低, 只不过表示它被允许允许的机会小一些而已。
线程的优先级设置可以为1-10的任一数值, Thread类中定义了三个线程优先级, 分别是:MIN_PRIORITY(1)、NORM_PRIORITY(5)、MAX_PRIORITY(10), 一般情况下推荐使用这几个常量, 不要自行设置数值。
不同平台, 对线程的优先级的支持不同, 编程的时候, 不要过度依赖线程优先级, 如果你的程序运行是否正确取决于你设置的优先级是否按所设置的优先级运行, 那这样的程序是不正确的
快速处理:设置高的优先级
慢慢处理:设置低的优先级
代码演示
/**
* 线程优先级Demo
*/
public class PriorityDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (true) {
System.out.println(Thread.currentThread().getName());
}
}, "线程1");
Thread thread2 = new Thread(() -> {
while (true) {
System.out.println(Thread.currentThread().getName());
}
}, "线程2");
thread.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread.start();
thread2.start();
}
}