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

Java 線程進階:優先級、同步、死鎖與生產消費模式

     編輯:Java 相關知識

1. 線程優先級

使用 setPriority(int) 設置,範圍 1-10,預設 5。高優先級線程獲得更多 CPU 時間片,但不保證執行順序。

t1.setPriority(Thread.NORM_PRIORITY + 3); // 優先級 8
t2.setPriority(Thread.NORM_PRIORITY);     // 優先級 5

2. 線程同步與 synchronized

通過 synchronized 鎖定共享資源,防止併發訪問導致數據不一致。

class Timer {
    private static int num = 0;
    public synchronized void add(String name) { // 或 synchronized(this)
        num++;
        System.out.println(name + ":第 " + num + " 個使用");
    }
}

3. 死鎖示例與避免

兩線程互相持有對方需要的鎖,導致永久等待。

// 線程 1
synchronized(o1) { sleep(500); synchronized(o2) { System.out.println("1"); } }
// 線程 2
synchronized(o2) { sleep(500); synchronized(o1) { System.out.println("0"); } }

避免策略:固定鎖獲取順序、使用 tryLock 超時機制、減少鎖範圍。

4. 生產者-消費者模式

使用 wait()/notify() 實現緩衝區協調。

class SyncStack {
    private int index = 0;
    private char[] data = new char[6];
    public synchronized void push(char c) {
        if (index == data.length) { wait(); }
        data[index++] = c;
        notify();
    }
    public synchronized char pop() {
        if (index == 0) { wait(); }
        notify();
        return data[--index];
    }
}

5. 關鍵點總結

  • sleep() 不釋放鎖;wait() 釋放鎖並進入等待隊列。
  • join() 合併線程,等待目標線程結束。
  • yield() 讓出 CPU,重新參與調度。
  • 死鎖核心條件:互斥、請求保持、不可剝奪、循環等待。

結語

掌握線程優先級控制、同步機制、死鎖預防與經典協作模式,是編寫健壯多線程程序的核心技能。

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