- 同步代碼塊的鎖可以是任意對象
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--);
}
}