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

Java 多執行緒程式設計基礎:建立、啟動、優先級與同步控制機制

     編輯:Java 相關知識

多執行緒基礎架構

Java 透過 Thread 類別與 Runnable 介面提供多執行緒支援。執行緒是 Thread 或其子類別的實例,核心在於 run() 方法定義任務邏輯。

1. 執行緒建立兩種方式

方式一:繼承 Thread 並覆寫 run()

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread running...");
    }
}

// 使用
Thread t1 = new MyThread();
t1.start(); // 啟動執行緒

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

class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable task running...");
    }
}

// 使用
Thread t2 = new Thread(new MyTask());
t2.start();

2. 啟動與執行機制

  • start():向 JVM 註冊執行緒,排程執行 run(),**非同步返回**。
  • 直接呼叫 run():單純方法呼叫,當前執行緒循序執行,**不會啟動新執行緒**。
  • 執行緒啟動後為 RUNNABLE 狀態,由作業系統排程器決定何時在 CPU 執行。

3. 執行緒優先級

  • 範圍:1~10,預設 5 (NORM_PRIORITY)。
  • setPriority(int) / getPriority()。
  • 高優先級執行緒獲得 CPU 時間機率較高,但**非保證**。
  • 可在啟動前或執行中動態調整。
Thread t1 = new MyThread();
Thread t2 = new Thread(new MyTask());
t1.setPriority(Thread.MAX_PRIORITY); // 10
t2.setPriority(Thread.MIN_PRIORITY); // 1
t1.start(); t2.start();

4. 同步控制核心機制

問題:非同步存取共享資料

執行緒 A 讀取資料,執行緒 B 同時修改 → 髒讀、更新遺失、不一致。

解決方案一:synchronized 關鍵字(監視器模式)

class DataStore {
    private int value = 0;
    
    // 同步方法:鎖定 this
    public synchronized void write(int v) {
        value = v;
    }
    
    public synchronized int read() {
        return value;
    }
}

解決方案二:wait/notify 協調機制

生產者-消費者經典模型:

class Warehouse {
    private int stock = 0;
    private final int CAPACITY = 10;
    
    public synchronized void produce() throws InterruptedException {
        while (stock >= CAPACITY) wait(); // 滿了等待
        stock++;
        notifyAll(); // 通知消費者
    }
    
    public synchronized void consume() throws InterruptedException {
        while (stock == 0) wait(); // 空了等待
        stock--;
        notifyAll(); // 通知生產者
    }
}

關鍵點

  • wait():釋放鎖,進入 WAITING,需在 synchronized 區塊呼叫。
  • notify():喚醒一個等待執行緒;notifyAll():喚醒全部。
  • 喚醒後需重新競爭鎖,檢查條件通常用 while 而非 if(防虛假喚醒)。

5. 完整範例:生產者消費者

class Producer extends Thread {
    private Warehouse warehouse;
    public Producer(Warehouse w) { warehouse = w; }
    public void run() {
        try { while (true) { warehouse.produce(); Thread.sleep(100); } }
        catch (InterruptedException ignored) {}
    }
}

class Consumer extends Thread {
    private Warehouse warehouse;
    public Consumer(Warehouse w) { warehouse = w; }
    public void run() {
        try { while (true) { warehouse.consume(); Thread.sleep(150); } }
        catch (InterruptedException ignored) {}
    }
}

public class Main {
    public static void main(String[] args) {
        Warehouse w = new Warehouse();
        new Producer(w).start();
        new Consumer(w).start();
    }
}

6. 現代替代方案(JDK 5+)

工具替代目標
ReentrantLocksynchronized(更多功能)
Conditionwait/notify
BlockingQueue生產者消費者手動實作
Semaphore資源許可控制
CountDownLatch執行緒等待計數
ExecutorService手動 Thread 管理

最佳實務總結

  1. 優先用 Runnable + 執行緒池,避免手動 Thread。
  2. 同步範圍最小化,鎖定具體物件而非整個方法。
  3. 共享資料用 volatile 確保可見性,複合操作用 synchronized/Lock。
  4. 生產者消費者直接用 BlockingQueue。
  5. 避免 stop/suspend/resume,用 interrupt() 協作式停止。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved