[Java-多線程]“基礎篇”04之 synchronized關鍵字

概要
本章,會對synchronized關鍵字進行介紹。涉及到的內容包括:
1. synchronized原理
2. synchronized基本規則
3. synchronized方法 和 synchronized代碼塊
4. 實例鎖 和 全局鎖
轉載請注明出處:http://www.cnblogs.com/skywang12345/p/3479202.html

1. synchronized原理
Java中,每一個對象有且僅有一個同步鎖。這也意味著,同步鎖是依賴于對象而存在。
當我們調用某對象的synchronized方法時,就獲取了該對象的同步鎖。例如,synchronized(obj)就獲取了“obj這個對象”的同步鎖。
不同線程對同步鎖的訪問是互斥的。也就是說,某時間點,對象的同步鎖只能被一個線程獲取到!通過同步鎖,我們就能在多線程中,實現對“對象/方法”的互斥訪問。 例如,現在有兩個線程A和線程B,它們都會訪問“對象obj的同步鎖”。假設,在某一時刻,線程A獲取到“obj的同步鎖”并在執行一些操作;而此時,線程B也企圖獲取“obj的同步鎖” —— 線程B會獲取失敗,它必須等待,直到線程A釋放了“該對象的同步鎖”之后線程B才能獲取到“obj的同步鎖”從而才可以運行。

2. synchronized基本規則
我們將synchronized的基本規則總結為下面3條,并通過實例對它們進行說明。
第一條: 當一個線程訪問“某對象”的“synchronized方法”或者“synchronized代碼塊”時,其他線程對“該對象”的該“synchronized方法”或者“synchronized代碼塊”的訪問將被阻塞。
第二條: 當一個線程訪問“某對象”的“synchronized方法”或者“synchronized代碼塊”時,其他線程仍然可以訪問“該對象”的非同步代碼塊
第三條: 當一個線程訪問“某對象”的“synchronized方法”或者“synchronized代碼塊”時,其他線程對“該對象”的其他的“synchronized方法”或者“synchronized代碼塊”的訪問將被阻塞。

第一條
當一個線程訪問“某對象”的“synchronized方法”或者“synchronized代碼塊”時,其他線程對“該對象”的該“synchronized方法”或者“synchronized代碼塊”的訪問將被阻塞。
下面是“synchronized代碼塊”對應的演示程序。

1 class MyRunable implements Runnable { 
2  
3    @Override 
4    public void run() { 
5       synchronized(this) { 
6       try {  
7          for (int i = 0; i < 5; i++) { 
8             Thread.sleep(100); // 休眠100ms 
9             System.out.println(Thread.currentThread().getName() + " loop " + i); 
10         }
11        } catch (InterruptedException ie) { 
12     }
13   } 
14  }
15 }
16 
17 public class Demo1_1 {
18 
19     public static void main(String[] args) { 
20         Runnable demo = new MyRunable(); // 新建“Runnable對象”
21 
22         Thread t1 = new Thread(demo, "t1"); // 新建“線程t1”, t1是基于demo這個Runnable對象
23         Thread t2 = new Thread(demo, "t2"); // 新建“線程t2”, t2是基于demo這個Runnable對象
24         t1.start(); // 啟動“線程t1”
25         t2.start(); // 啟動“線程t2” 
26    } 
27 }

運行結果
t1 loop 0
t1 loop 1
t1 loop 2
t1 loop 3
t1 loop 4
t2 loop 0
t2 loop 1
t2 loop 2
t2 loop 3
t2 loop 4

結果說明
run()方法中存在“synchronized(this)代碼塊”,而且t1和t2都是基于"demo這個Runnable對象"創建的線程。這就意味著,我們可以將synchronized(this)中的this看作是“demo這個Runnable對象”;因此,線程t1和t2共享“demo對象的同步鎖”。所以,當一個線程運行的時候,另外一個線程必須等待“運行線程”釋放“demo的同步鎖”之后才能運行。
如果你確認,你搞清楚這個問題了。那我們將上面的代碼進行修改,然后再運行看看結果怎么樣,看看你是否會迷糊。修改后的源碼如下:

1 class MyThread extends Thread { 
2  
3    public MyThread(String name) { 
4       super(name); 
5     } 
6  
7    @Override 
8    public void run() { 
9       synchronized(this) {
10       try { 
11          for (int i = 0; i < 5; i++) {
12             Thread.sleep(100); // 休眠100ms
13             System.out.println(Thread.currentThread().getName() + " loop " + i); 
14           }
15       } catch (InterruptedException ie) { 
16       }
17     } 
18   }
19 }
20 
21 public class Demo1_2 {
22 
23    public static void main(String[] args) { 
24    Thread t1 = new MyThread("t1"); // 新建“線程t1”
25    Thread t2 = new MyThread("t2"); // 新建“線程t2”
26    t1.start(); // 啟動“線程t1”
27    t2.start(); // 啟動“線程t2” 
28  } 
29 }

代碼說明
比較Demo1_2 和 Demo1_1,我們發現,Demo1_2中的MyThread類是直接繼承于Thread,而且t1和t2都是MyThread子線程。
幸運的是,在“Demo1_2的run()方法”也調用了synchronized(this),正如“Demo1_1的run()方法”也調用了synchronized(this)一樣!那么,Demo1_2的執行流程是不是和Demo1_1一樣呢?
運行結果:
t1 loop 0
t2 loop 0
t1 loop 1
t2 loop 1
t1 loop 2
t2 loop 2
t1 loop 3
t2 loop 3
t1 loop 4
t2 loop 4

結果說明
如果這個結果一點也不令你感到驚訝,那么我相信你對synchronized和this的認識已經比較深刻了。否則的話,請繼續閱讀這里的分析。
synchronized(this)中的this是指“當前的類對象”,即synchronized(this)所在的類對應的當前對象。它的作用是獲取“當前對象的同步鎖”。
對于Demo1_2中,synchronized(this)中的this代表的是MyThread對象,而t1和t2是兩個不同的MyThread對象,因此t1和t2在執行synchronized(this)時,獲取的是不同對象的同步鎖。對于Demo1_1對而言,synchronized(this)中的this代表的是MyRunable對象;t1和t2共同一個MyRunable對象,因此,一個線程獲取了對象的同步鎖,會造成另外一個線程等待。

第二條
當一個線程訪問“某對象”的“synchronized方法”或者“synchronized代碼塊”時,其他線程仍然可以訪問“該對象”的非同步代碼塊。下面是“synchronized代碼塊”對應的演示程序。

1 class Count { 
2  
3     // 含有synchronized同步塊的方法 
4     public void synMethod() { 
5         synchronized(this) { 
6         try {  
7             for (int i = 0; i < 5; i++) { 
8                 Thread.sleep(100); // 休眠100ms 
9                 System.out.println(Thread.currentThread().getName() + " synMethod loop " + i); 
10              }
11             } catch (InterruptedException ie) { 
12             }
13          } 
14       }
15 
16     // 非同步的方法
17     public void nonSynMethod() {
18         try { 
19             for (int i = 0; i < 5; i++) {
20                 Thread.sleep(100);
21                 System.out.println(Thread.currentThread().getName() + " nonSynMethod loop " + i); 
22              }
23         } catch (InterruptedException ie) { 
24       }
25      }
26 }
27 
28 public class Demo2 {
29 
30     public static void main(String[] args) { 
31         final Count count = new Count();
32         // 新建t1, t1會調用“count對象”的synMethod()方法
33         Thread t1 = new Thread(
34         new Runnable() {
35              @Override
36             public void run() {
37                  count.synMethod();
38              }
39         }, "t1");
40 
41         // 新建t2, t2會調用“count對象”的nonSynMethod()方法
42         Thread t2 = new Thread(
43             new Runnable() {
44             @Override
45             public void run() {
46                  count.nonSynMethod();
47              }
48         }, "t2"); 
49 
50 
51         t1.start(); // 啟動t1
52         t2.start(); // 啟動t2
53      } 
54 }

運行結果
t1 synMethod loop 0
t2 nonSynMethod loop 0
t1 synMethod loop 1
t2 nonSynMethod loop 1
t1 synMethod loop 2
t2 nonSynMethod loop 2
t1 synMethod loop 3
t2 nonSynMethod loop 3
t1 synMethod loop 4
t2 nonSynMethod loop 4

結果說明
主線程中新建了兩個子線程t1和t2。t1會調用count對象的synMethod()方法,該方法內含有同步塊;而t2則會調用count對象的nonSynMethod()方法,該方法不是同步方法。
t1運行時,雖然調用synchronized(this)獲取“count的同步鎖”;但是并沒有造成t2的阻塞,因為t2沒有用到“count”同步鎖。

第三條
當一個線程訪問“某對象”的“synchronized方法”或者“synchronized代碼塊”時,其他線程對“該對象”的其他的“synchronized方法”或者“synchronized代碼塊”的訪問將被阻塞。
我們將上面的例子中的nonSynMethod()方法體的也用synchronized(this)修飾。修改后的源碼如下:

 1 class Count { 
2  
3 // 含有synchronized同步塊的方法 
4 public void synMethod() { 
5 synchronized(this) { 
6 try {  
7 for (int i = 0; i < 5; i++) { 
8 Thread.sleep(100); // 休眠100ms 
9 System.out.println(Thread.currentThread().getName() + " synMethod loop " + i); 
10  }
11 } catch (InterruptedException ie) { 
12  }
13  } 
14  }
15 
16 // 也包含synchronized同步塊的方法
17 public void nonSynMethod() {
18 synchronized(this) {
19 try { 
20 for (int i = 0; i < 5; i++) {
21 Thread.sleep(100);
22 System.out.println(Thread.currentThread().getName() + " nonSynMethod loop " + i); 
23  }
24 } catch (InterruptedException ie) { 
25  }
26  }
27  }
28 }
29 
30 public class Demo3 {
31 
32 public static void main(String[] args) { 
33 final Count count = new Count();
34 // 新建t1, t1會調用“count對象”的synMethod()方法
35 Thread t1 = new Thread(
36 new Runnable() {
37  @Override
38 public void run() {
39  count.synMethod();
40  }
41 }, "t1");
42 
43 // 新建t2, t2會調用“count對象”的nonSynMethod()方法
44 Thread t2 = new Thread(
45 new Runnable() {
46  @Override
47 public void run() {
48  count.nonSynMethod();
49  }
50 }, "t2"); 
51 
52 
53 t1.start(); // 啟動t1
54 t2.start(); // 啟動t2
55  } 
56 }

運行結果
t1 synMethod loop 0
t1 synMethod loop 1
t1 synMethod loop 2
t1 synMethod loop 3
t1 synMethod loop 4
t2 nonSynMethod loop 0
t2 nonSynMethod loop 1
t2 nonSynMethod loop 2
t2 nonSynMethod loop 3
t2 nonSynMethod loop 4

結果說明
主線程中新建了兩個子線程t1和t2。t1和t2運行時都調用synchronized(this),這個this是Count對象(count),而t1和t2共用count。因此,在t1運行時,t2會被阻塞,等待t1運行釋放“count對象的同步鎖”,t2才能運行。

3. synchronized方法 和 synchronized代碼塊
“synchronized方法”是用synchronized修飾方法,而 “synchronized代碼塊”則是用synchronized修飾代碼塊。
synchronized方法示例

public synchronized void foo1() { 
  System.out.println("synchronized methoed");
}

synchronized代碼塊

public void foo2() { 
  synchronized (this) { 
      System.out.println("synchronized methoed"); 
   }
}

synchronized代碼塊中的this是指當前對象。也可以將this替換成其他對象,例如將this替換成obj,則foo2()在執行synchronized(obj)時就獲取的是obj的同步鎖。
synchronized代碼塊可以更精確的控制沖突限制訪問區域,有時候表現更高效率。
下面通過一個示例來演示:

 1 // Demo4.java的源碼 
2 public class Demo4 { 
3  
4 public synchronized void synMethod() { 
5 for(int i=0; i<1000000; i++) 
6  ; 
7  } 
8  
9 public void synBlock() {
10 synchronized( this ) {
11 for(int i=0; i<1000000; i++)
12  ;
13  }
14  }
15 
16 public static void main(String[] args) {
17 Demo4 demo = new Demo4();
18 
19 long start, diff;
20 start = System.currentTimeMillis(); // 獲取當前時間(millis)
21 demo.synMethod(); // 調用“synchronized方法”
22 diff = System.currentTimeMillis() - start; // 獲取“時間差值”
23 System.out.println("synMethod() : "+ diff);
24 
25 start = System.currentTimeMillis(); // 獲取當前時間(millis)
26 demo.synBlock(); // 調用“synchronized方法塊”
27 diff = System.currentTimeMillis() - start; // 獲取“時間差值”
28 System.out.println("synBlock() : "+ diff);
29  }
30 }

(某一次)執行結果
synMethod() : 11
synBlock() : 3

4. 實例鎖 和 全局鎖
**實例鎖 **-- 鎖在某一個實例對象上。如果該類是單例,那么該鎖也具有全局鎖的概念。 實例鎖對應的就是synchronized關鍵字。
全局鎖 -- 該鎖針對的是類,無論實例多少個對象,那么線程都共享該鎖。 全局鎖對應的就是static synchronized(或者是鎖在該類的class或者classloader對象上)。
關于“實例鎖”和“全局鎖”有一個很形象的例子:

pulbic class Something { 
public synchronized void isSyncA(){} 
public synchronized void isSyncB(){} 
public static synchronized void cSyncA(){} 
public static synchronized void cSyncB(){}
}

假設,Something有兩個實例x和y。分析下面4組表達式獲取的鎖的情況。
(01) x.isSyncA()與x.isSyncB()
(02) x.isSyncA()與y.isSyncA()
(03) x.cSyncA()與y.cSyncB()
(04) x.isSyncA()與Something.cSyncA()
(01) 不能被同時訪問。因為isSyncA()和isSyncB()都是訪問同一個對象(對象x)的同步鎖!

 1 // LockTest1.java的源碼 
2 class Something { 
3 public synchronized void isSyncA(){ 
4 try {  
5 for (int i = 0; i < 5; i++) { 
6 Thread.sleep(100); // 休眠100ms 
7 System.out.println(Thread.currentThread().getName()+" : isSyncA"); 
8  } 
9 }catch (InterruptedException ie) { 
10  } 
11  }
12 public synchronized void isSyncB(){
13 try { 
14 for (int i = 0; i < 5; i++) {
15 Thread.sleep(100); // 休眠100ms
16 System.out.println(Thread.currentThread().getName()+" : isSyncB");
17  }
18 }catch (InterruptedException ie) { 
19  } 
20  }
21 }
22 
23 public class LockTest1 {
24 
25 Something x = new Something();
26 Something y = new Something();
27 
28 // 比較(01) x.isSyncA()與x.isSyncB() 
29 private void test1() {
30 // 新建t11, t11會調用 x.isSyncA()
31 Thread t11 = new Thread(
32 new Runnable() {
33  @Override
34 public void run() {
35  x.isSyncA();
36  }
37 }, "t11");
38 
39 // 新建t12, t12會調用 x.isSyncB()
40 Thread t12 = new Thread(
41 new Runnable() {
42  @Override
43 public void run() {
44  x.isSyncB();
45  }
46 }, "t12"); 
47 
48 
49 t11.start(); // 啟動t11
50 t12.start(); // 啟動t12
51  }
52 
53 public static void main(String[] args) {
54 LockTest1 demo = new LockTest1();
55  demo.test1();
56  }
57 }

運行結果
t11 : isSyncA
t11 : isSyncA
t11 : isSyncA
t11 : isSyncA
t11 : isSyncA
t12 : isSyncB
t12 : isSyncB
t12 : isSyncB
t12 : isSyncB
t12 : isSyncB

(02) 可以同時被訪問。因為訪問的不是同一個對象的同步鎖,x.isSyncA()訪問的是x的同步鎖,而y.isSyncA()訪問的是y的同步鎖。

 1 // LockTest2.java的源碼 2 class Something { 3 public synchronized void isSyncA(){ 4 try {  5 for (int i = 0; i < 5; i++) { 6 Thread.sleep(100); // 休眠100ms 7 System.out.println(Thread.currentThread().getName()+" : isSyncA"); 8  } 9 }catch (InterruptedException ie) { 10  } 11  }12 public synchronized void isSyncB(){13 try { 14 for (int i = 0; i < 5; i++) {15 Thread.sleep(100); // 休眠100ms16 System.out.println(Thread.currentThread().getName()+" : isSyncB");17  }18 }catch (InterruptedException ie) { 19  } 20  }21 public static synchronized void cSyncA(){22 try { 23 for (int i = 0; i < 5; i++) {24 Thread.sleep(100); // 休眠100ms25 System.out.println(Thread.currentThread().getName()+" : cSyncA");26  } 27 }catch (InterruptedException ie) { 28  } 29  }30 public static synchronized void cSyncB(){31 try { 32 for (int i = 0; i < 5; i++) {33 Thread.sleep(100); // 休眠100ms34 System.out.println(Thread.currentThread().getName()+" : cSyncB");35  } 36 }catch (InterruptedException ie) { 37  } 38  }39 }40 41 public class LockTest2 {42 43 Something x = new Something();44 Something y = new Something();45 46 // 比較(02) x.isSyncA()與y.isSyncA()47 private void test2() {48 // 新建t21, t21會調用 x.isSyncA()49 Thread t21 = new Thread(50 new Runnable() {51  @Override52 public void run() {53  x.isSyncA();54  }55 }, "t21");56 57 // 新建t22, t22會調用 x.isSyncB()58 Thread t22 = new Thread(59 new Runnable() {60  @Override61 public void run() {62  y.isSyncA();63  }64 }, "t22"); 65 66 67 t21.start(); // 啟動t2168 t22.start(); // 啟動t2269  }70 71 public static void main(String[] args) {72 LockTest2 demo = new LockTest2();73 74  demo.test2();75  }76 }

運行結果
t21 : isSyncA
t22 : isSyncA
t21 : isSyncA
t22 : isSyncA
t21 : isSyncA
t22 : isSyncA
t21 : isSyncA
t22 : isSyncA
t21 : isSyncA
t22 : isSyncA

(03) 不能被同時訪問。因為cSyncA()和cSyncB()都是static類型,x.cSyncA()相當于Something.isSyncA(),y.cSyncB()相當于Something.isSyncB(),因此它們共用一個同步鎖,不能被同時反問。

 1 // LockTest3.java的源碼 2 class Something { 3 public synchronized void isSyncA(){ 4 try {  5 for (int i = 0; i < 5; i++) { 6 Thread.sleep(100); // 休眠100ms 7 System.out.println(Thread.currentThread().getName()+" : isSyncA"); 8  } 9 }catch (InterruptedException ie) { 10  } 11  }12 public synchronized void isSyncB(){13 try { 14 for (int i = 0; i < 5; i++) {15 Thread.sleep(100); // 休眠100ms16 System.out.println(Thread.currentThread().getName()+" : isSyncB");17  }18 }catch (InterruptedException ie) { 19  } 20  }21 public static synchronized void cSyncA(){22 try { 23 for (int i = 0; i < 5; i++) {24 Thread.sleep(100); // 休眠100ms25 System.out.println(Thread.currentThread().getName()+" : cSyncA");26  } 27 }catch (InterruptedException ie) { 28  } 29  }30 public static synchronized void cSyncB(){31 try { 32 for (int i = 0; i < 5; i++) {33 Thread.sleep(100); // 休眠100ms34 System.out.println(Thread.currentThread().getName()+" : cSyncB");35  } 36 }catch (InterruptedException ie) { 37  } 38  }39 }40 41 public class LockTest3 {42 43 Something x = new Something();44 Something y = new Something();45 46 // 比較(03) x.cSyncA()與y.cSyncB()47 private void test3() {48 // 新建t31, t31會調用 x.isSyncA()49 Thread t31 = new Thread(50 new Runnable() {51  @Override52 public void run() {53  x.cSyncA();54  }55 }, "t31");56 57 // 新建t32, t32會調用 x.isSyncB()58 Thread t32 = new Thread(59 new Runnable() {60  @Override61 public void run() {62  y.cSyncB();63  }64 }, "t32"); 65 66 67 t31.start(); // 啟動t3168 t32.start(); // 啟動t3269  }70 71 public static void main(String[] args) {72 LockTest3 demo = new LockTest3();73 74  demo.test3();75  }76 }

運行結果
t31 : cSyncA
t31 : cSyncA
t31 : cSyncA
t31 : cSyncA
t31 : cSyncA
t32 : cSyncB
t32 : cSyncB
t32 : cSyncB
t32 : cSyncB
t32 : cSyncB

(04) 可以被同時訪問。因為isSyncA()是實例方法,x.isSyncA()使用的是對象x的鎖;而cSyncA()是靜態方法,Something.cSyncA()可以理解對使用的是“類的鎖”。因此,它們是可以被同時訪問的。

 1 // LockTest4.java的源碼 2 class Something { 3 public synchronized void isSyncA(){ 4 try {  5 for (int i = 0; i < 5; i++) { 6 Thread.sleep(100); // 休眠100ms 7 System.out.println(Thread.currentThread().getName()+" : isSyncA"); 8  } 9 }catch (InterruptedException ie) { 10  } 11  }12 public synchronized void isSyncB(){13 try { 14 for (int i = 0; i < 5; i++) {15 Thread.sleep(100); // 休眠100ms16 System.out.println(Thread.currentThread().getName()+" : isSyncB");17  }18 }catch (InterruptedException ie) { 19  } 20  }21 public static synchronized void cSyncA(){22 try { 23 for (int i = 0; i < 5; i++) {24 Thread.sleep(100); // 休眠100ms25 System.out.println(Thread.currentThread().getName()+" : cSyncA");26  } 27 }catch (InterruptedException ie) { 28  } 29  }30 public static synchronized void cSyncB(){31 try { 32 for (int i = 0; i < 5; i++) {33 Thread.sleep(100); // 休眠100ms34 System.out.println(Thread.currentThread().getName()+" : cSyncB");35  } 36 }catch (InterruptedException ie) { 37  } 38  }39 }40 41 public class LockTest4 {42 43 Something x = new Something();44 Something y = new Something();45 46 // 比較(04) x.isSyncA()與Something.cSyncA()47 private void test4() {48 // 新建t41, t41會調用 x.isSyncA()49 Thread t41 = new Thread(50 new Runnable() {51  @Override52 public void run() {53  x.isSyncA();54  }55 }, "t41");56 57 // 新建t42, t42會調用 x.isSyncB()58 Thread t42 = new Thread(59 new Runnable() {60  @Override61 public void run() {62  Something.cSyncA();63  }64 }, "t42"); 65 66 67 t41.start(); // 啟動t4168 t42.start(); // 啟動t4269  }70 71 public static void main(String[] args) {72 LockTest4 demo = new LockTest4();73 74  demo.test4();75  }76 }

運行結果
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容