首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

[JAVA100例] 第67例:線程優先級調度演示

     編輯:Java 相關知識

本例演示通過設置線程優先級影響 CPU 調度:兩個線程同時運行,先均為最低優先級,後將線程 2 提升至最高優先級,觀察輸出頻率變化。

核心代碼

import java.util.*;

public class upPRIThread {
  public static void main(String[] args) throws Exception {
    Thread1 t1 = new Thread1();
    t1.start();
    Thread2 t2 = new Thread2();
    t2.start();

    t1.setPriority(Thread.MIN_PRIORITY);  // 1
    t2.setPriority(Thread.MIN_PRIORITY);  // 1
    new Thread().sleep(105);              // 短暫運行

    t2.setPriority(Thread.MAX_PRIORITY);  // 10
    new Thread().sleep(10500);            // 長時間觀察
  }

  static class Thread1 extends Thread {
    public void run() {
      while (true) {
        try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); }
        System.out.println("我是線程111");
      }
    }
  }

  static class Thread2 extends Thread {
    public void run() {
      while (true) {
        try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); }
        System.out.println("我是線程222.........................");
      }
    }
  }
}

關鍵概念

  • 優先級範圍:MIN_PRIORITY=1、NORM_PRIORITY=5、MAX_PRIORITY=10
  • 設置方法:thread.setPriority(int),需在 start() 前或運行中調用
  • 調度提示:優先級是「提示」而非強制保證,具體表現依賴 JVM 實現與操作系統調度策略

預期現象

  1. 前 105ms:兩線程優先級相同,輸出大致交替
  2. 後 10.5s:線程 2 優先級最高,理論上獲得更多 CPU 時間片,"線程222" 輸出頻率顯著高於 "線程111"

現代並發最佳實踐

  • 避免依賴優先級:跨平台行為不一,不可作為核心同步手段
  • 使用 ExecutorService:ThreadPoolExecutor 統一管理線程生命週期
  • 併發工具類:CountDownLatch、CyclicBarrier、Semaphore、CompletableFuture 解決協調問題
  • 虛擬線程:JDK 21+ Thread.ofVirtual() 輕量級線程,優先級概念弱化

代碼改進建議

  1. 使用 Thread.currentThread().sleep() 替代 new Thread().sleep()(後者創建臨時線程無意義)
  2. 添加 volatile boolean running 標誌優雅停止線程
  3. 使用 TimeUnit.MILLISECONDS.sleep() 可讀性更好
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved