深入理解Java 02 內建鎖與死結

來源:互聯網
上載者:User

一、並發問題分析

如果一個類或者程式所提供的介面對於線程來說是原子操作,或者多個線程之間的切換不會導致該介面的執行結果存在二義性,也就是說我們不用考慮同步的問題,此時線程是安全的。

而實際中存在這樣的情況:
1.存在兩個或者兩個以上的線程對象,而且線程之間共用著一個資源。
2.有多個語句操作了共用資源。

二、解決方案

用一個案例來說明:張劉亮和鄭旭共用一包面紙,兩個人相當於兩個線程,每一張紙不可以兩人同時抽取
方式一:同步代碼塊
線程類:


class PaperThread extends Thread{
        
     static int num = 100;//紙的數量  非靜態成員變數,非靜態成員變數資料是在每個對象中都會維護一份資料的。
     
     static Object o = new Object();
    
     public PaperThread (String name) {
        super(name);
     }
    
    @Override
    public void run() {
        while(true){
            //同步代碼塊
            synchronized ("鎖") {              
                if(num>0){                   
                    System.out.println(Thread.currentThread().getName()
                    +"取走了1張紙,還剩"+(count-1)+"張"");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    num--;
                }else{
                    System.out.println("用光了..");
                    break;
                }
            }     
        }
    }     
}

測試類別
    
public class Test{
    public static void main(String[] args) {
        //建立兩個線程
        PaperThread thread1 = new PaperThread("張劉亮");
        PaperThread thread2 = new PaperThread("鄭旭");
        //開啟線程
        thread1.start();
        thread2.start();      
    } 
}

同步代碼塊要注意事項:

1. 任意的一個對象都可以做為鎖對象。
2. 在同步代碼塊中調用了sleep方法並不是釋放鎖對象的。
3. 只有真正存線上程安全問題的時候才使用同步代碼塊,否則會降低效率的。
4. 多線程操作的鎖對象必須是唯一共用的,否則無效。

方式二:同步函數:同步函數就是使用synchronized修飾一個函數。
線程類:


class PaperThread extends Thread{
    
    static int count = 100;
    
    public currentThread(String name){
        super(name);
    }
    
    //@Override
    public synchronized  void run() {
        getPaper();
    } 
    
    //靜態函數---->函數所屬的類的位元組碼檔案對象--->PaperThread.class 唯一的。
    public static synchronized void getPaper(){
        while(true){          
            if(count>0){
                 System.out.println(Thread.currentThread().getName()
                         +"取走了1張紙,還剩"+ (count-1)+"張");
             count= count - 1000;
            }else{
               System.out.println("紙用光了...");
               break;
            } 
        }
    } 
}
測試類別:

public class Test {
 
    public static void main(String[] args) {
        //建立兩個線程對象
        PaperThread thread1 = new PaperThread("張劉亮");
        PaperThread thread2 = new PaperThread("鄭旭");
        //調用start方法開啟線程取錢
        thread1.start();
        thread2.start();      
    } 
}
同步函數要注意的事項 :
1. 如果是一個非靜態同步函數的鎖對象是this對象,如果是靜態同步函數的鎖 對象是當前函數所屬的類的位元組碼檔案(class對象)。
2. 同步函數的鎖對象是固定的,不能由你來指定的。

推薦使用:同步代碼塊。
原因:
1. 同步代碼塊的鎖對象可以由我們隨意指定,方便控制。同步函數的鎖對象是固定的,不能由我們來指定。
2. 同步代碼塊可以很方便控制需要被同步代碼的範圍,同步函數必須是整個函數的所有代碼都被同步了。

三、死結

同步機制解決了安全執行緒問題,但是也同時引發死結現象。
案例:張劉亮和鄭旭打LOL,只有一個滑鼠和一個鍵盤,需要同時擷取滑鼠和鍵盤才能打LOL


class DeadLock extends Thread{
    
    public DeadLock(String name){
        super(name);
    }
    
    public void run() {
        if("張劉亮".equals(Thread.currentThread().getName())){
            synchronized ("鍵盤") {
                System.out.println("張劉亮拿到了鍵盤,準備去拿滑鼠");
                synchronized ("滑鼠") {
                    System.out.println("張劉亮拿到了鍵盤和滑鼠,擼了起來");
                }
            }
        }else if("鄭旭".equals(Thread.currentThread().getName())){
            synchronized ("滑鼠") {
                System.out.println("鄭旭拿到了滑鼠,準備去拿鍵盤");
                synchronized ("鍵盤") {
                    System.out.println("鄭旭拿到了鍵盤和滑鼠,擼了起來");
                }
            }     
        } 
    }
}


public class TestDeadLock {
 
    public static void main(String[] args) {
        DeadLock thread1 = new DeadLock("張劉亮");
        DeadLock thread2 = new DeadLock("鄭旭");
        //開啟線程
        thread1.start();
        thread2.start();      
        
    }
    
}
死結現象出現 的根本原因:
1. 存在兩個或者兩個以上的線程。
2. 存在兩個或者兩個以上的共用資源。
死結現象的解決方案:死結沒有解決方案,只能盡量避免。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.