线程优先级 其实是一个(概率问题)
目录
什么是线程优先级
- 代表该线程的重要程度。如果有大量线程都被堵塞,都在等待运行,会尽可能的运行优先级高的线程。
- 优先级越高的线程获取CPU时间片的次数越多,优先级较低的线程不代表不会运行,只是机会小。
- 优先级可以设置,不建议自己设置,线程分为10个优先级,分别用整数1-10表示,其中1为最低优先级,5为默认值,10为最高优先级
- 不同平台,对线程优先级的支持不同,编程的时候不要过度依赖线程优先级。
图解:
线程优先级设置
在 Java 中,可以通过 setPriority(int newPriority) 方法来设置线程的优先级:
代码实例:
package com.day0430;
public class Priority1 {
public static void main(String[] args) {
System.out.println("线程 main的优先级:" + Thread.currentThread().getPriority());
Thread thread = new Thread("a") {
@Override
public void run() {
System.out.println("线程"+Thread.currentThread().getName()+"的优先级:" + this.getPriority());
}
};
thread.start();
}
}
控制台打印:
代码实例:
package com.day0430;
public class Priority2 {
public static void main(String[] args) {
System.out.println("线程 main的优先级:" + Thread.currentThread().getPriority());
Thread.currentThread().setPriority(6);
System.out.println("设置优先级");
System.out.println("线程 main的优先级:" + Thread.currentThread().getPriority());
Thread thread = new Thread("a") {
@Override
public void run() {
System.out.println("线程"+Thread.currentThread().getName()+"的优先级:" + this.getPriority());
}
};
thread.start();
}
}
控制台输出:
Ending..
我是小天,路虽远 行必至,各位的喜爱是对我最大的鼓励,我们下篇文章见~
...