优先级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 2022-02-07 15:55  周文豪  阅读(210)  评论(0编辑  收藏  举报