【多线程】线程优先级 Priority

线程优先级 Priority

  1. Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度 器按照优先级决定应该调度哪个线程来执行。

  2. 线程的优先级用数字表示,范围从1~10。

    • Thread.MIN_PRIORITY = 1;
    • Thread.MAX_PRIORITY = 10;
    • Thread.NORM_PRIORITY = 5;
  3. 使用以下方式改变或获取优先级:

    getPriority() //获取优先级

    setPriority(int xxx) //设置优先级

  4. 优先级的设定建议在start()调度前;

  5. 优先级低只是意味着获得调度的 概率低,并不是优先级低就不会 被调用了,这都是看CPU的调度。

代码示例:

/**
* @Description 测试线程的优先级
* @Author hzx
* @Date 2022-03-27
*/
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"默认优先级-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
//先设置优先级,再启动
t1.start(); //未设置,默认优先级
t2.setPriority(Thread.MIN_PRIORITY); //最小优先级 MIN_PRIORITY=1
t2.start();
t3.setPriority(Thread.MAX_PRIORITY); //最大优先级 MAX_PRIORITY=10
t3.start();
t4.setPriority(3);
t4.start();
t5.setPriority(8);
t5.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程优先级-->"+Thread.currentThread().getPriority());
}
}

执行结果:

main默认优先级-->5
Thread-0线程优先级-->5
Thread-1线程优先级-->1
Thread-4线程优先级-->8
Thread-2线程优先级-->10
Thread-3线程优先级-->3
posted @   HZX↑  阅读(115)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示