什么是线程优先级?
线程的优先级就是告诉程序每个线程的重要程度。如果有大量的线程被堵塞,都在等待运行,程序会尽可能地运行优先级高的那个线程。但是并不代表优先级低的线程不会运行,只是说优先级低的线程被允许执行的概率会比高优先级线程允许执行的概率低。
查看Thread源码可以看到,线程优先级最大是10, 最小是1 ,默认是5,一般情况下推荐使用下面三个常量,不要自行设置数值。
/**
* 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;
下面看两个简单的例子
1.未设置优先级是运行两个线程
public class PriorityDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
while (true){
try {
Thread.sleep(300l);
System.out.println(Thread.currentThread().getName());
}catch (InterruptedException e){
e.printStackTrace();
}
}
},"线程1");
Thread thread2 = new Thread(()->{
while (true) {
try {
Thread.sleep(300l);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"线程2");
thread1.start();
thread2.start();
}
}
运行结果:
线程2
线程1
线程2
线程1
线程2
线程1
线程2
线程1
2.设置最大最小等级的两个线程
public class PriorityDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
while (true){
try {
Thread.sleep(300l);
System.out.println(Thread.currentThread().getName());
}catch (InterruptedException e){
e.printStackTrace();
}
}
},"线程1");
Thread thread2 = new Thread(()->{
while (true) {
try {
Thread.sleep(300l);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"线程2");
thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
}
}
运行结果:
线程2
线程2
线程1
线程2
线程1
通过查看上面两个简单的例子,发现基本符合上面的理论说明。
不同的平台,对线程优先级的支持不同。编程的时候,不要过度的依赖线程的优先级。