2. 單個線程中可以使用synchronized,而且可以嵌套,但無意義. class Test { public static void main(String[] args) { Test t = new Test(); synchronized(t) { synchronized(t) { System.out.PRintln("ok!"); } } } }
3. 對象實例的鎖 class Test{ public synchronized void f1(){ //do something here }
public void f2(){ synchronized(this){ //do something here } } }
上面的f1()和f2()效果一致, synchronized取得的鎖都是Test某個實列(this)的鎖. 比如: Test t = new Test(); 線程A調用t.f2()時, 線程B無法進入t.f1(),直到t.f2()結束.
作用: 多線程中訪問Test的同一個實例的同步方法時會進行同步.
4. class的鎖 class Test{ final static Object o= new Object();
public static synchronized void f1(){ //do something here }
public static void f2(){ synchronized(Test.class){ //do something here } }
public static void f3(){ try { synchronized (Class.forName("Test")) { //do something here } } catch (ClassNotFoundException ex) { } }
public static void g(){ synchronized(o){ //do something here } } }