随笔 - 754  文章 - 0 评论 - 33 阅读 - 135万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

优先级priority:当线程需要竞争CPU资源时,优先级高的能分配更多的CPU资源

现今操作系统基本采用分时的形式调度运行的线程,线程分配得到时间片的多少决定了线程使用处理器资源的多少,也对应了线程优先级这个概念。

分时调度:所有线程轮流使用 CPU 的使用权,平均分配每个线程占用 CPU 的时间。

在JAVA线程中,通过一个int priority来控制优先级,范围为1-10,其中10最高,默认值为5

复制代码
public class Demo10Priority {
  public static void main(String[] args) {
    PrioritytThread prioritytThread = new PrioritytThread();
    // 如果8核CPU处理3线程,无论优先级高低,每个线程都是单独一个CPU执行,就无法体现优先级
    // 开启10个线程,让8个CPU处理,这里线程就需要竞争CPU资源,优先级高的能分配更多的CPU资源
    for (int i = 0; i < 10; i++) {
      Thread t = new Thread(prioritytThread, "线程" + i);
      if (i == 1) {
        t.setPriority(10);
     }
      if (i == 2) {
        t.setPriority(1);
     }
      t.setDaemon(true); // 设置用户线程为守护线程,即主线程停止,用户线程也停止
      t.start();
   }
    try {
      Thread.sleep(1000l);
   } catch (InterruptedException e) {
      e.printStackTrace();
   }
    System.out.println("线程1总计:" + PrioritytThread.count1);
    System.out.println("线程2总计:" + PrioritytThread.count2);
 }
  static class PrioritytThread implements Runnable {
    public static Integer count1 = 0;
    public static Integer count2 = 0;
    public void run() {
      while (true) {
        if ("线程1".equals(Thread.currentThread().getName())) {
          count1++;
       }
        if ("线程2".equals(Thread.currentThread().getName())) {
          count2++;
       }
        if (Thread.currentThread().isInterrupted()) {
          break;
       }
     }
   }
 }
}
复制代码

结果如下:

线程1总计:80536263
线程2总计:3173022

 



感谢您的阅读,如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮。本文欢迎各位转载,但是转载文章之后必须在文章页面中给出作者和原文连接
posted on   周文豪  阅读(222)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2021-02-07 Mysql训练:第二高的薪水(IFNULL,OFFSET,LIMIT)
点击右上角即可分享
微信分享提示