1. 程式人生 > 程式設計 >Java多執行緒的臨界資源問題解決方案

Java多執行緒的臨界資源問題解決方案

這篇文章主要介紹了Java多執行緒的臨界資源問題解決方案,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

臨界資源問題的原因:某一個執行緒在對臨界資源進行訪問時,還沒來得及完全修改臨界資源的值,臨界資源就被其他執行緒拿去訪問,導致多個執行緒訪問同一資源。直觀表現為列印結果順序混亂。

解決方法:加鎖

靜態方法中用類鎖,非靜態方法中用物件鎖。

1.同步程式碼段:synchronized(){...}

2.同步方法:使用關鍵字synchronized修飾的方法

3.使用顯式同步鎖ReentrantLock

鎖池描述的即為鎖外等待的狀態

方法一:同步程式碼段:synchronized(){...}

public class SourceConflict {
  public static void main(String[] args) {
    //例項化4個售票員,用4個執行緒模擬4個售票員
    
    Runnable r = () -> {
      while (TicketCenter.restCount > 0) {
        synchronized(" ") {
          if (TicketCenter.restCount <= 0) {
            return;
          }
          System.out.println(Thread.currentThread().getName() + "賣出一張票,剩餘" + --TicketCenter.restCount + "張票");
        }
      }
    };
    
    //用4個執行緒模擬4個售票員
    Thread thread1 = new Thread(r,"thread-1");
    Thread thread2 = new Thread(r,"thread-2");
    Thread thread3 = new Thread(r,"thread-3");
    Thread thread4 = new Thread(r,"thread-4");
    
    //開啟執行緒
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
    
  }  
}

//實現四名售票員共同售票,資源共享,非獨立
//Lambda表示式或匿名內部類內部捕獲的區域性變數必須顯式的宣告為 final 或實際效果的的 final 型別,而捕獲例項或靜態變數是沒有限制的
class TicketCenter{
  public static int restCount = 100; 
}

方法二:同步方法,即使用關鍵字synchronized修飾的方法

public class SourceConflict2 {
  public static void main(String[] args) {
    //例項化4個售票員,用4個執行緒模擬4個售票員
    
    Runnable r = () -> {
      while (TicketCenter.restCount > 0) {
        sellTicket();
      }
    };
    
    //用4個執行緒模擬4個售票員
    Thread thread1 = new Thread(r,"thread-4");
    
    //開啟執行緒
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
    
  }
  
  private synchronized static void sellTicket() {  
    if (TicketCenter.restCount <= 0) {
      return;
    }
    System.out.println(Thread.currentThread().getName() + "賣出一張票,剩餘" + --TicketCenter.restCount + "張票");
  }
}

class TicketCenter{
  public static int restCount = 100; 
}

方法三:使用顯式同步鎖ReentrantLock

import java.util.concurrent.locks.ReentrantLock;

public class SourceConflict3 {
  public static void main(String[] args) {
    //例項化4個售票員,用4個執行緒模擬4個售票員
    
    //顯式鎖
    ReentrantLock lock = new ReentrantLock();
    Runnable r = () -> {
      while (TicketCenter.restCount > 0) {
        lock.lock();
        if (TicketCenter.restCount <= 0) {
          return;
        }
        System.out.println(Thread.currentThread().getName() + "賣出一張票,剩餘" + --TicketCenter.restCount + "張票");
        lock.unlock();
      }
    };
    
    //用4個執行緒模擬4個售票員
    Thread thread1 = new Thread(r,"thread-4");
    
    //開啟執行緒
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
    
  }  
}
class TicketCenter{
  public static int restCount = 100; 
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。