- 同步代码块的锁可以是任意对象
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--);
}
}