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

Java 入門筆記:多線程程式設計核心概念與實作

     編輯:Java 相關知識

1. 建立線程類別的兩種方式

1.1 繼承 Thread 類別

public class MyFirstThread extends Thread {
    public void run() { /* 執行緒本體 */ }
}
  • Thread 在 java.lang,無需 import。
  • 必須覆寫 run() 放入執行碼。
  • 啟動:new MyFirstThread().start();(start() 會呼叫 run() 在新執行緒執行)。
  • 其他方法:stop()、suspend()、resume()(已棄用)。

完整範例:ComplexThread

public class ComplexThread extends Thread {
    private int delay;
    ComplexThread(String name, float seconds) {
        super(name);
        delay = (int) (seconds * 1000);
        start(); // 自動啟動
    }
    public void run() {
        while (true) {
            System.out.println(Thread.currentThread().getName());
            try { Thread.sleep(delay); }
            catch (InterruptedException e) { return; }
        }
    }
    public static void main(String[] argv) {
        new ComplexThread("one potato", 1.1f);
        new ComplexThread("two potato", 1.3f);
        new ComplexThread("three potato", 0.5f);
        new ComplexThread("four", 0.7f);
    }
}

1.2 實作 Runnable 介面

public class MySecondThread extends ImportantClass implements Runnable {
    public void run() { ... }
}
  • 實作 Runnable 表示意圖在獨立執行緒執行(Thread 本身也實作 Runnable)。
  • 至少須實作 run()。

啟動方式

MySecondThread mst = new MySecondThread();
Thread t = new Thread(mst);
t.start();
  • 使用 Thread(Runnable target) 建構子。
  • t.start() 呼叫 target.run()。
  • 建構子可指定名稱、堆疊大小、執行緒群組。

防止非正常結束

try { myThread.start(); }
catch (ThreadDeath td) {
    System.out.println("end Thread");
    throw td; // 重拋讓 JVM 執行清理
}

2. 執行緒優先權

  • 範圍 1~10:MIN_PRIORITY=1、NORM_PRIORITY=5、MAX_PRIORITY=10。預設 NORM_PRIORITY。
  • 非搶佔式系統:高優先權執行緒可能佔用 CPU,低優先權無法執行。
  • 解決:在 run() 中呼叫 Thread.yield() 或 Thread.sleep() 讓出 CPU。
  • setPriority() 可動態調整:t1.setPriority(t2.getPriority() + 1)。
  • join():等待指定執行緒結束。try { t.join(); } catch (InterruptedException e) {}

3. synchronized 關鍵字與線程安全

3.1 同步方法

public synchronized void countMe() {
    crucialValue += 1; // 三步驟變原子操作
}

3.2 同步區塊(鎖定物件)

synchronized(p) {
    safeX = p.x();
    safeY = p.y(); // 區塊期間 p 不可被其他執行緒修改
}

3.3 保護類別變數(static 欄位)

public class StaticCounter {
    private static int crucialValue;
    public void countMe() {
        synchronized (getClass()) { // 或 Class.forName("StaticCounter")
            crucialValue += 1;
        }
    }
}
  • static 欄位屬於類別,所有實例共享。
  • 同步鎖需用 getClass() 或 Class.forName() 取得 Class 物件,不可直接用類別名稱。

4. 執行緒狀態與生命週期

新建 → 就緒 → 執行 → 阻塞/等待/睡眠 → 結束。yield() 讓出 CPU 回就緒態;sleep() 進入計時等待;wait()/notify() 配合物件鎖進行協調(屬於 Object 方法)。

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