本例演示通過設置線程優先級影響 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=10thread.setPriority(int),需在 start() 前或運行中調用ThreadPoolExecutor 統一管理線程生命週期CountDownLatch、CyclicBarrier、Semaphore、CompletableFuture 解決協調問題Thread.ofVirtual() 輕量級線程,優先級概念弱化Thread.currentThread().sleep() 替代 new Thread().sleep()(後者創建臨時線程無意義)volatile boolean running 標誌優雅停止線程TimeUnit.MILLISECONDS.sleep() 可讀性更好