当前位置: 首页 > news >正文

线程优先级

线程可以通过设置优先级来控制获得CPU的概率,注意这里只是概率,如果低优先级的线程很早到达,且能被分到CPU那么此时低优先的线程会比高优先级但后到来的线程更早运行
可以通过getPrioritysetPriority 来获取和设置线程的优先级

    /*** 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;

由官方文档不难看出,线程优先级的设置只能在[1, 10]之间,超过会抛出异常

public class ThreadPriority {public static void main(String[] args) {System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());MyThread myThread = new MyThread();Thread thread1 = new Thread(myThread);Thread thread2 = new Thread(myThread);Thread thread3 = new Thread(myThread);Thread thread4 = new Thread(myThread);// 先设置优先级,再启动thread1.start();thread2.setPriority(1);thread2.start();thread3.setPriority(4);thread3.start();thread4.setPriority(Thread.MAX_PRIORITY);thread4.start();}
}

通过上面的程序我们可能会观测到线程优先级带来的变化,但是一定可以得到的是,线程的默认优先级是5,也就是NORM_PRIORITY

http://www.jsqmd.com/news/29343/

相关文章:

  • 使用 GeckoCircuits 设计 Buck 电源环路
  • 第k小的数的分治算法
  • Day29-C:\Users\Lenovo\Desktop\note\code\JavaSE\Basic\src\com\reflect
  • k8s-Pod中的网络通信(3)
  • 一个灵感:思维的断章
  • 第十届中国大学生程序设计竞赛 哈尔滨站(CCPC 2024 Harbin Site)
  • CSP-S 回顾
  • https://heylink.me/tizihacks/
  • 2025CSP-J游记
  • 通达信:引用函数 - Leone
  • 20231427田泽航第七周预习报告
  • CSP总结
  • AI泡沫再思考:技术革命与投资狂潮的真相
  • [群表示论]基本概念
  • P14362 [CSP-S 2025] 道路修复
  • 10.30总结
  • 基于 Maxwell 实现 MySQL 数据实时迁移到 Mongodb
  • CSP2025-S 坠机记
  • jenkins安装排错
  • 一、RK3562板卡上手
  • 【题解】CCPC 2024 Jinan Site [J] Temperance
  • 2025 年 11 月金属件去毛刺机,五金去毛刺机,自动去毛刺机厂家最新推荐,聚焦资质、案例、售后的五家机构深度解读!
  • 原来求凸包这么简单
  • 2025 年 11 月全自动激光去毛刺机,金属件去毛刺机,自动去毛刺机厂家最新推荐,精准检测与稳定性能深度解析!
  • 2025 年 11 月数控激光去毛刺机,冲压件去毛刺机,精密去毛刺机厂家最新推荐,实力品牌深度解析采购无忧之选!
  • AT ARC156C Tree and LCS 题解
  • 2025 年 11 月回转式风机厂家最新推荐,实力品牌深度解析采购无忧之选!
  • CSPT漏洞浅析
  • 【题解】CCPC 2024 Jinan Site [F] The Hermit
  • Ubunt 搭建Samba服务