多线程优先级 详细知识点 全是干货 Java17

默认的优先级

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 怎么分配了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值