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

Java 多執行緒核心詳解:建立、生命週期、同步、通訊與生產消費模型

     編輯:Java 程式設計入門

建立執行緒的兩種方式

1. 繼承 Thread 類別

class Demo extends Thread {
    public void run() {
        for (int i = 0; i < 60; i++) 
            System.out.println(Thread.currentThread().getName() + i);
    }
}
new Demo().start();

2. 實作 Runnable 介面

class Demo2 implements Runnable {
    public void run() { ... }
}
new Thread(new Demo2()).start();

本質上皆需建立 Thread 實例。Runnable 更彈性,避免單一繼承限制。

執行緒生命週期與控制方法

  • 新建 → 就緒:start()
  • 就緒 → 執行:排程器調度
  • 執行 → 阻塞:sleep(), wait(), I/O 等待
  • 阻塞 → 就緒:時間到、notify()、I/O 就緒
  • 執行 → 終止:run() 結束、interrupt()、stop()(不建議)

關鍵方法:sleep() 需捕捉 InterruptedException;join() 使呼叫執行緒等待目標執行緒結束(異步變同步)。

執行緒安全與同步機制

問題根源

多執行緒操作共享資料,指令非原子性導致資料競爭。

解決方案

同步區塊

synchronized (lockObject) {
    // 臨界區
}

同步方法

public synchronized void saleTicket() { ... }
// 非靜態鎖 this,靜態鎖 Class 物件

售票範例

class Ticket implements Runnable {
    private int ticket = 400;
    public void run() {
        while (true) {
            synchronized (this) {
                if (ticket <= 0) break;
                System.out.println(Thread.currentThread().getName() + "---賣出" + ticket--);
            }
        }
    }
}

執行緒間通訊:wait / notify / notifyAll

必須在同一把鎖(synchronized 同一物件)內呼叫。

等待喚醒機制範例

synchronized (p) {
    if (flag) p.wait();          // 等待
    // 生產/消費邏輯
    flag = !flag;
    p.notifyAll();               // 喚醒所有等待執行緒
}

生產者-消費者模型(多生產多消費)

class Goods {
    private String name; private int num; private boolean flag = false;
    public synchronized void produce(String name) {
        while (flag) wait();
        this.name = name + "編號:" + num++;
        System.out.println(Thread.currentThread().getName() + "生產了..." + this.name);
        flag = true; notifyAll();
    }
    public synchronized void consume() {
        while (!flag) wait();
        System.out.println(Thread.currentThread().getName() + "消費了*****" + name);
        flag = false; notifyAll();
    }
}
// 啟動 2 生產者 + 2 消費者

輸出顯示嚴格交替生產消費,驗證同步正確性。

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