同步代碼塊、同步函數和靜態同步函數

  • 同步代碼塊的鎖可以是任意對象
Object obj = new Object();
synchronized(obj)
{
    if(num > 0)
    {
        try{Thread.sleep(10);} catch(InterruptedException e){};
        System.out.println(Thread.currentThread().getName() + "......obj......" + num--);
    }
}	
  • 同步函數的鎖是固定的的this(同步函數是同步代碼塊的簡寫形式)
public synchronized void show()
{
    if(num > 0)
    {
        try{Thread.sleep(10);} catch(InterruptedException e){};
        System.out.println(Thread.currentThread().getName() + "......function......" + num--);
    }
}
  • 靜態同步函數使用的鎖是該函數所屬字節碼文件對象,可以使用this.getClass()方法獲取,也可以用當前 類名.class表示。

靜態方法中沒有this對象,靜態方法沒有所屬對象。而任何類在加載的時候都會有字節碼類對象,用getClass獲取。

public static synchronized void show()//靜態方法中沒有this對象,靜態方法沒有所屬對象//任何類在加載的時候都會有字節碼類對象,用getClass獲取。
{
    if(num > 0)
    {
        try{Thread.sleep(10);} catch(InterruptedException e){};
        System.out.println(Thread.currentThread().getName() + "......function......" + num--);
    }
}



發佈了49 篇原創文章 · 獲贊 19 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章