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

Java 多執行緒建立兩大範式與優先級機制詳解

     編輯:Java 相關知識

建立執行緒的兩種標準方式

方式一:繼承 Thread 類別

class MyThread extends Thread {
    public void run() { /* 執行邏輯 */ }
}

// 使用
MyThread t1 = new MyThread();
t1.start();
  • 每個實例獨擁資源(如各自 100 張票),適合獨立任務。
  • 缺點:Java 單一繼承限制,無法再繼承其他類別。

方式二:實作 Runnable 介面(推薦)

class MyTask implements Runnable {
    private int ticket = 100; // 共享資源
    public void run() { /* 存取 ticket */ }
}

// 使用:同一任務實例建立多個執行緒
MyTask task = new MyTask();
new Thread(task, "Window-1").start();
new Thread(task, "Window-2").start();
new Thread(task, "Window-3").start();
  • 多執行緒共享同一任務實例,自然實現資源共享(如售票系統共用票池)。
  • 解耦「任務邏輯」與「執行機制」,符合 OOP 原則,支援執行緒池、Lambda 表達式(Java 8+)。

進階寫法:Runnable 內部封裝 Thread

class MyTask implements Runnable {
    private Thread t;
    MyTask(String name) { t = new Thread(this, name); }
    public void start() { t.start(); }
    public void run() { /* ... */ }
}

執行緒優先級機制

  • 範圍:MIN_PRIORITY(1) ~ MAX_PRIORITY(10),預設 NORM_PRIORITY(5)。
  • 子執行緒繼承建立者優先級(主執行緒預設 5)。
  • setPriority(int)、getPriority() 動態調整。

優先級影響示範

Thread t1 = new Thread(() -> { while(running) count1++; }, "Low");
Thread t2 = new Thread(() -> { while(running) count2++; }, "High");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start(); t2.start();
Thread.sleep(1000);
running = false;
System.out.println("Low: " + count1 + ", High: " + count2); // High 顯著較大

優先級的侷限性與最佳實務

  • 平台相依:Windows/Linux 排程器對優先級映射不同,不可倚賴精確控制。
  • 飢餓風險:高優先級佔用 CPU 導致低優先級長期無法執行。
  • 建議:
    1. 多用 yield() 主動讓出 CPU(同優先級)。
    2. 採用 ExecutorService + ThreadFactory 統一管理優先級。
    3. 真正需要即時性時,考慮 ReentrantLock 公平鎖或即時作業系統(RTSJ)。

總結

實作 Runnable 是建立執行緒的主流範式,支援資源共享與解耦。優先級僅為排程「提示」,不可作為正確性保證;生產環境請改用高階並發套件(java.util.concurrent)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved