synchronized是一個重量級鎖,我們都知道該關鍵字鎖住的是對象而不是代碼本身,那么對於靜態方法和同步方法有什么不同呢,通過如下代碼進行測試

1 public class SynchronizedTest { 2 3 private static int num; 4 5 private synchronized void test(String param){ 6 if(StringUtils.equals(param,"a")){ 7 num = 100; 8 System.out.println("set " + param + " num over"); 9 try { 10 Thread.sleep(1000); 11 } catch (InterruptedException e) { 12 e.printStackTrace(); 13 } 14 }else{ 15 num = 200; 16 System.out.println("set " + param + " num over"); 17 } 18 System.out.println("i am : " + param + "; num = " + num); 19 } 20 21 public static void main(String[] args){ 22 SynchronizedTest s1 = new SynchronizedTest(); 23 SynchronizedTest s2 = new SynchronizedTest(); 24 25 new Thread(new Runnable() { 26 @Override 27 public void run() { 28 s1.test("a"); 29 } 30 }).start(); 31 32 new Thread(new Runnable() { 33 @Override 34 public void run() { 35 s2.test("b"); 36 } 37 }).start(); 38 } 39 }

set a num over set b num over i am : b; num = 200 i am : a; num = 200 Process finished with exit code 0
我們可以看出兩個不同的對象s1和s2並沒有互斥,因為這里synchronized是分別持有兩個對象的鎖。如果要想m1,m2兩個對象競爭同一個鎖,則需要在method01()上加上static修飾,如下:

1 public class SynchronizedTest { 2 3 private static int num; 4 5 private synchronized static void test(String param){ 6 if(StringUtils.equals(param,"a")){ 7 num = 100; 8 System.out.println("set " + param + " num over"); 9 try { 10 Thread.sleep(1000); 11 } catch (InterruptedException e) { 12 e.printStackTrace(); 13 } 14 }else{ 15 num = 200; 16 System.out.println("set " + param + " num over"); 17 } 18 System.out.println("i am : " + param + "; num = " + num); 19 } 20 21 public static void main(String[] args){ 22 SynchronizedTest s1 = new SynchronizedTest(); 23 SynchronizedTest s2 = new SynchronizedTest(); 24 25 new Thread(new Runnable() { 26 @Override 27 public void run() { 28 s1.test("a"); 29 } 30 }).start(); 31 32 new Thread(new Runnable() { 33 @Override 34 public void run() { 35 s2.test("b"); 36 } 37 }).start(); 38 } 39 }
運行結果:

set a num over i am : a; num = 100 set b num over i am : b; num = 200 Process finished with exit code 0
synchronized修飾不加static的方法,鎖是加在單個對象上,不同的對象沒有競爭關系;修飾加了static的方法,鎖是加載類上,這個類所有的對象競爭一把鎖.
版權聲明:本文為CSDN博主「珍惜每一個遇見」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/LQM1991/article/details/86143278