自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

詳解synchronized鎖的各種用法及注意事項(xiàng)

開發(fā) 后端
本文主要通過簡(jiǎn)單的demo來闡述synchronized鎖的各種用法以及使用synchronized鎖的相關(guān)注意事項(xiàng),記錄下來同時(shí)也方便自己記憶。

 [[440304]]

1 前言

本文主要通過簡(jiǎn)單的demo來闡述synchronized鎖的各種用法以及使用synchronized鎖的相關(guān)注意事項(xiàng),記錄下來同時(shí)也方便自己記憶。

synchronized鎖是jvm內(nèi)置的鎖,不同于ReentrantLock鎖。synchronized關(guān)鍵字可以修飾方法,也可以修飾代碼塊。synchronized關(guān)鍵字修飾方法時(shí)可以修飾靜態(tài)方法,也可以修飾非靜態(tài)方法;同樣,synchronized關(guān)鍵字修飾代碼塊時(shí)可以修飾對(duì)象,也可以修飾類。當(dāng)然,synchronized修飾靜態(tài)方法/類和非靜態(tài)方法/對(duì)象時(shí)的作用范圍是不同的。下面通過各種demo來詳解synchronized的各種用法及注意事項(xiàng)。

2 synchronized類鎖

這里所說的synchronized類鎖的作用范圍是類級(jí)別的,不會(huì)因?yàn)橥粋€(gè)類的不同對(duì)象執(zhí)行而失效。

2.1 synchronized修飾同一個(gè)類的兩個(gè)靜態(tài)方法時(shí)互斥 

  1. public class SynchronizeAndClassLock {  
  2.     public static void main(String[] args) throws Exception {  
  3.         new Thread(() -> {  
  4.             // new了一個(gè)ClassLock對(duì)象  
  5.             new ClassLock().test1();  
  6.         }).start();  
  7.         new Thread(() -> {  
  8.             // new了另一個(gè)ClassLock對(duì)象  
  9.             new ClassLock().test2();  
  10.         }).start();  
  11.     } 
  12.  
  13. class ClassLock {  
  14.     public synchronized static void test1(){  
  15.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  16.         try {  
  17.             TimeUnit.SECONDS.sleep(1);  
  18.         } catch (Exception e) {}  
  19.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  20.     }  
  21.  // 【注意】public static void test2(){ 不會(huì)互斥,因?yàn)榇藭r(shí)test2沒有使用類鎖。  
  22.     public synchronized static void test2(){ 
  23.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  24.         try {  
  25.             TimeUnit.SECONDS.sleep(1);  
  26.         } catch (Exception e) {}  
  27.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  28.     }  

運(yùn)行結(jié)果:

【結(jié)論】?jī)蓚€(gè)線程分別同時(shí)執(zhí)行同一個(gè)類產(chǎn)生的不同對(duì)象的兩個(gè)不同 synchronized static方法,類鎖生效,雖然是不同對(duì)象,因?yàn)閮蓚€(gè)線程使用的是同一個(gè)類鎖。反過來,假如test2方法沒有synchronized修飾的話,只有test1方法有被synchronized修飾,此時(shí)兩個(gè)方法也不會(huì)互斥,一個(gè)有鎖,一個(gè)沒有鎖,自然不會(huì)互斥。

2.2 synchronized分別修飾同一個(gè)類的靜態(tài)方法和當(dāng)前類時(shí)互斥 

  1. public class SynchronizeAndClassLock2 {  
  2.     public static void main(String[] args) throws Exception {  
  3.         new Thread(() -> {  
  4.             // new了一個(gè)ClassLock2對(duì)象  
  5.             new ClassLock2().test1();  
  6.             // ClassLock2.test1(); 
  7.         }).start();  
  8.         new Thread(() -> {  
  9.             // new了另一個(gè)ClassLock2對(duì)象  
  10.             new ClassLock2().test2();  
  11.             // ClassLock2.test2();  
  12.         }).start();  
  13.     } 
  14.  
  15. class ClassLock2 {  
  16.     public synchronized static void test1(){  
  17.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  18.         try {  
  19.             TimeUnit.SECONDS.sleep(1);  
  20.         } catch (Exception e) {}  
  21.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  22.     } 
  23.     public static void test2(){  
  24.      // 【注意】synchronized (SynchronizeAndClassLock2.class)不會(huì)互斥  
  25.         synchronized (ClassLock2.class) {  
  26.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  27.             try { 
  28.                 TimeUnit.SECONDS.sleep(1);  
  29.             } catch (Exception e) {}  
  30.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  31.         }  
  32.     }  

運(yùn)行結(jié)果:

【結(jié)論】?jī)蓚€(gè)線程同時(shí)分別執(zhí)行一個(gè)被synchronized修飾static方法,一個(gè)有synchnized(該類)代碼塊的static方法,鎖生效,雖然是不同對(duì)象,因?yàn)閮蓚€(gè)線程使用的同一個(gè)類鎖。反過來,如果是修飾的不同類,因?yàn)轭愭i不同,肯定不會(huì)互斥,比如將test2方法的synchronized (ClassLock2.class)這句代碼改成synchronized (SynchronizeAndClassLock2.class),此時(shí)不會(huì)互斥。

2.3 synchronized分別修飾同一個(gè)靜態(tài)對(duì)象時(shí)互斥 

  1. public class SynchronizeAndClassLock10 {  
  2.     public static void main(String[] args) throws Exception {  
  3.         new Thread(() -> {  
  4.             new RunObject1().test1();  
  5.         }).start();  
  6.         new Thread(() -> {  
  7.             new RunObject2().test2();  
  8.         }).start();  
  9.     }  
  10.  
  11. class RunObject1 {  
  12.     public static void test1(){  
  13.      // 【1】synchronized (StaticLock2.staticLock1) {  
  14.         synchronized (StaticLock2.staticLock) {  
  15.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  16.             try {  
  17.                 TimeUnit.SECONDS.sleep(1);  
  18.             } catch (Exception e) {}  
  19.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  20.         }  
  21.     }  
  22.  
  23. class RunObject2 {  
  24.     public static void test2() {  
  25.      // 【2】synchronized (StaticLock2.staticLock2) {  
  26.         synchronized (StaticLock2.staticLock) {  
  27.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  28.             try {  
  29.                 TimeUnit.SECONDS.sleep(1);  
  30.             } catch (Exception e) {}  
  31.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  32.         }  
  33.     }  
  34.  
  35. class StaticLock2 {  
  36.     public static Object staticLock = new Object();  

運(yùn)行結(jié)果:

【結(jié)論】synchronized分別修飾同一個(gè)類的靜態(tài)對(duì)象時(shí)互斥,反過來,如果是修飾不同的靜態(tài)對(duì)象,肯定不會(huì)互斥,比如將上面代碼中標(biāo)【1】和【2】的synchronized代碼結(jié)合使用。

3 synchronized對(duì)象鎖

這里說的synchronized對(duì)象鎖的作用范圍是對(duì)象級(jí)別的即僅僅作用于同一個(gè)對(duì)象,如果是同一個(gè)類的兩個(gè)不同的對(duì)象是不會(huì)互斥的,即沒有效果的。

3.1 synchronized修飾同一個(gè)類對(duì)象的兩個(gè)非靜態(tài)方法時(shí)互斥 

  1. public class SynchronizeAndObjectLock2 {  
  2.     public static void main(String[] args) throws Exception {  
  3.         // 【注意】當(dāng)且僅當(dāng)是同一個(gè)SynchronizeAndObjectLock2對(duì)象  
  4.         SynchronizeAndObjectLock2 synchronizeAndObjectLock2 = new SynchronizeAndObjectLock2();  
  5.         new Thread(() -> { 
  6.             synchronizeAndObjectLock2.test1();  
  7.         }).start();  
  8.         new Thread(() -> {  
  9.             synchronizeAndObjectLock2.test2();  
  10.         }).start();  
  11.     }  
  12.     public synchronized void test1(){  
  13.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  14.         try {  
  15.             TimeUnit.SECONDS.sleep(1);  
  16.         } catch (Exception e) {}  
  17.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  18.     }  
  19.     public synchronized void test2(){  
  20.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  21.         try {  
  22.             TimeUnit.SECONDS.sleep(1);  
  23.         } catch (Exception e) {} 
  24.          System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  25.     }  

運(yùn)行結(jié)果:

【結(jié)論】?jī)蓚€(gè)線程同時(shí)執(zhí)行被synchronized修飾的相同對(duì)象的不同(相同)方法,鎖生效,因?yàn)閮蓚€(gè)線程使用的是相同的對(duì)象鎖

3.2 synchronized分別修飾同一個(gè)類對(duì)象的非靜態(tài)方法和當(dāng)前對(duì)象時(shí)互斥 

  1. public class SynchronizeAndObjectLock3 {  
  2.     public static void main(String[] args) throws Exception {  
  3.         // 【注意】當(dāng)且僅當(dāng)是同一個(gè)SynchronizeAndObjectLock3對(duì)象  
  4.         SynchronizeAndObjectLock3 synchronizeAndObjectLock3 = new SynchronizeAndObjectLock3();  
  5.         new Thread(() -> {  
  6.             synchronizeAndObjectLock3.test1();  
  7.         }).start(); 
  8.         new Thread(() -> {  
  9.             synchronizeAndObjectLock3.test2();  
  10.         }).start();  
  11.     }  
  12.     public void test1(){  
  13.         synchronized(this) {  
  14.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  15.             try {  
  16.                 TimeUnit.SECONDS.sleep(1);  
  17.             } catch (Exception e) {}  
  18.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  19.         } 
  20.     }  
  21.     public synchronized void test2(){  
  22.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  23.         try { 
  24.             TimeUnit.SECONDS.sleep(1);  
  25.         } catch (Exception e) {}  
  26.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  27.     } 
  28.  

運(yùn)行結(jié)果:

【結(jié)論】snchronized修飾非靜態(tài)方法與synchronized(this)互斥,可見,snchronized修飾非靜態(tài)方法實(shí)質(zhì)鎖的是當(dāng)前對(duì)象。

3.3 synchronized修飾不同對(duì)象的兩個(gè)非靜態(tài)方法時(shí)不會(huì)互斥 

  1. public class SynchronizeAndObjectLock {  
  2.     public static void main(String[] args) throws Exception {  
  3.         new Thread(() -> {  
  4.             // 這里new 了一個(gè)SynchronizeAndObjectLock對(duì)象  
  5.             new SynchronizeAndObjectLock().test1();  
  6.         }).start();  
  7.         new Thread(() -> {  
  8.             // 這里new 了另一個(gè)SynchronizeAndObjectLock對(duì)象  
  9.             new SynchronizeAndObjectLock().test2();  
  10.         }).start();  
  11.     }  
  12.     public synchronized void test1(){  
  13.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  14.         try {  
  15.             TimeUnit.SECONDS.sleep(1);  
  16.         } catch (Exception e) {}  
  17.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  18.     } 
  19.     public synchronized void test2(){  
  20.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  21.         try {  
  22.             TimeUnit.SECONDS.sleep(1);  
  23.         } catch (Exception e) {}  
  24.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  25.     }  

運(yùn)行結(jié)果:

【結(jié)論】?jī)蓚€(gè)線程同時(shí)執(zhí)行被synchronized修飾的不同對(duì)象的不同(相同)方法,鎖未生效,因?yàn)閮蓚€(gè)線程使用的是不同的對(duì)象鎖。

3.4 synchronized代碼塊修飾同一個(gè)對(duì)象時(shí)互斥 

  1. public class SynchronizeAndObjectLock5 {  
  2.     private Object objectLock = new Object();  
  3.     public static void main(String[] args) throws Exception {      
  4.         SynchronizeAndObjectLock5 synchronizeAndObjectLock5 = new SynchronizeAndObjectLock5();  
  5.         new Thread(() -> {  
  6.             synchronizeAndObjectLock5.test1();  
  7.         }).start();  
  8.         new Thread(() -> {  
  9.             synchronizeAndObjectLock5.test2();  
  10.         }).start();  
  11.     }  
  12.     public void test1(){  
  13.         synchronized(objectLock) {  
  14.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  15.             try {  
  16.                 TimeUnit.SECONDS.sleep(1);  
  17.             } catch (Exception e) {}  
  18.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  19.         }  
  20.     }  
  21.     public void test2(){  
  22.         synchronized(objectLock) {  
  23.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  24.             try {  
  25.                 TimeUnit.SECONDS.sleep(1);  
  26.             } catch (Exception e) {}  
  27.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  28.         }  
  29.     }  

運(yùn)行結(jié)果

【結(jié)論】synchronized代碼塊修飾同一個(gè)對(duì)象時(shí)互斥,若synchronized代碼塊修飾的是不同對(duì)象,那么不會(huì)互斥。

4 synchronized修飾當(dāng)前類和當(dāng)前對(duì)象時(shí)不會(huì)互斥 

  1. public class ClassAndObjectLock {  
  2.     public static void main(String[] args) throws Exception {  
  3.         new Thread(() -> {  
  4.             ClassAndObjectLock.test1();  
  5.         }).start();  
  6.         new Thread(() -> {  
  7.             new ClassAndObjectLock().test2();  
  8.         }).start();  
  9.     }  
  10.     public static void test1(){  
  11.         synchronized (ClassAndObjectLock.class) {  
  12.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  13.             try {  
  14.                 TimeUnit.SECONDS.sleep(1);  
  15.             } catch (Exception e) {}  
  16.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  17.         }  
  18.     }  
  19.     public void test2(){  
  20.         synchronized (this) {  
  21.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin...");  
  22.             try {  
  23.                 TimeUnit.SECONDS.sleep(1);  
  24.             } catch (Exception e) {}  
  25.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " end...");  
  26.         }  
  27.     }  

運(yùn)行結(jié)果:

【結(jié)論】可見,類鎖和對(duì)象鎖是相互獨(dú)立的,互不相斥。

5 synchronized鎖注意事項(xiàng)

5.1 synchronized鎖不能被中斷

為了模擬synchronized鎖不可中斷,下面先讓兩個(gè)線程進(jìn)入死鎖,然后再用main線程去中斷其中一個(gè)線程,看被中斷的線程能否釋放鎖并被喚醒。 

  1. public class DeadLockCannotInterruptDemo {  
  2.     private static Object lock1 = new Object();  
  3.     private static Object lock2 = new Object();  
  4.     public static void main(String[] args) throws Exception {  
  5.         Thread threadA = new Thread(new Runnable() {  
  6.             @Override  
  7.             public void run() {  
  8.                 synchronized (lock1) {  
  9.                     System.out.println(Thread.currentThread().getName() + " get lock1");  
  10.                     try {  
  11.                         Thread.sleep(10);  
  12.                         synchronized (lock2) {  
  13.                             System.out.println(Thread.currentThread().getName() + " get lock2");  
  14.                         } 
  15.                      } catch (InterruptedException e) {  
  16.                         e.printStackTrace();  
  17.                     }  
  18.                 }  
  19.             }  
  20.         }); 
  21.         Thread threadB = new Thread(new Runnable() {  
  22.             @Override  
  23.             public void run() {  
  24.                 synchronized (lock2) {  
  25.                     System.out.println(Thread.currentThread().getName() + " get lock2");  
  26.                     try {  
  27.                         Thread.sleep(10);  
  28.                         synchronized (lock1) {  
  29.                             System.out.println(Thread.currentThread().getName() + " get lock1");  
  30.                         }  
  31.                     } catch (InterruptedException e) {  
  32.                         e.printStackTrace();  
  33.                     }  
  34.                 }  
  35.             }  
  36.         });  
  37.         threadA.start();  
  38.         threadB.start();  
  39.         TimeUnit.SECONDS.sleep(3);  
  40.         System.out.println("main thread begin to interrupt " + threadA.getName() + " and " + threadA.getName() + " will release lock1...");  
  41.         threadA.interrupt();  
  42.     } 

運(yùn)行結(jié)果:

【結(jié)論】如上圖,main線程中斷Thread-0后,Thread-0并不會(huì)釋放鎖并醒過來。同樣的,ReentrantLock的tryLock或lockInterruptibly是可以被中斷的。

5.2 synchronized鎖可重入

5.2.1 不同方法,synchronized是可重入的 

  1. public class SynchronizeAndReentrant {  
  2.     public static void main(String[] args) throws Exception {  
  3.         SynchronizeAndReentrant synchronizeAndReentrant = new SynchronizeAndReentrant();  
  4.         synchronizeAndReentrant.test1();  
  5.     } 
  6.     public synchronized void test1(){  
  7.         System.out.println(" test1 method is called...");  
  8.         test2();  
  9.     }  
  10.     public synchronized void test2(){  
  11.         System.out.println(" test2 method is called...");  
  12.     }  

運(yùn)行結(jié)果:

5.2.2 相同方法,synchronized是可重入的 

  1. public class SynchronizeAndReentrant2 {  
  2.     int i = 1 
  3.     public static void main(String[] args) throws Exception {  
  4.         SynchronizeAndReentrant2 synchronizeAndReentrant = new SynchronizeAndReentrant2();  
  5.         synchronizeAndReentrant.test1();  
  6.     }  
  7.     public synchronized void test1(){  
  8.         System.out.println(" test1 method is called " + i++ + "st time..." );  
  9.         while(i < 5) {  
  10.             test1();  
  11.         }  
  12.     }  

運(yùn)行結(jié)果:

5.3 synchronized鎖不帶超時(shí)功能

synchronized鎖不帶超時(shí)功能,而ReentrantLock的tryLock是具備帶超時(shí)功能的,在指定時(shí)間沒獲取到鎖,該線程會(huì)蘇醒,有助于預(yù)防死鎖的產(chǎn)生。

5.4 喚醒/等待需要synchronized鎖 

  1. public class NotifyNeedSynchronized {  
  2.     public static Object lock = new Object();  
  3.     public static void main(String[] args) throws Exception{  
  4.         // 拋出IllegalMonitorStateException  
  5.         //lock.notify();  
  6.         lock.wait();  
  7.     }  

運(yùn)行結(jié)果:

【結(jié)論】使用Object的notify和wait等方法時(shí),必須要使用synchronized鎖,否則會(huì)拋出IllegalMonitorStateException。

5.5 使用synchronized鎖時(shí)盡量縮小范圍以保證性能

使用synchronized鎖時(shí),為了盡可能提高性能,我們應(yīng)該盡量縮小鎖的范圍。能不鎖方法就不鎖方法,推薦盡量使用synchronized代碼塊來降低鎖的范圍。以下面的一段netty源碼為例: 

  1. // ServerBootstrap.java  
  2. public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value) {  
  3.     if (childOption == null) {  
  4.         throw new NullPointerException("childOption");  
  5.     }  
  6.     if (value == null) {  
  7.         synchronized (childOptions) {  
  8.             childOptions.remove(childOption);  
  9.         }  
  10.     } else {  
  11.         synchronized (childOptions) {  
  12.             childOptions.put(childOption, value);  
  13.         }  
  14.     }  
  15.     return this;  

可見,找到并發(fā)訪問代碼的臨界區(qū),并不用synchronized鎖全部代碼,盡量避免使用synchronized來修飾方法。

6 總結(jié)

本文對(duì)synchronized的各種用法及注意事項(xiàng)通過demo簡(jiǎn)單梳理了下,后面有時(shí)間會(huì)探討下synchronized的原理。 

 

責(zé)任編輯:龐桂玉 來源: Java知音
相關(guān)推薦

2021-02-07 07:40:31

Synchronize用法

2011-06-23 11:15:25

SEO網(wǎng)站優(yōu)化

2009-10-22 14:07:15

布線施工注意事項(xiàng)

2010-06-10 13:11:23

2011-11-23 09:02:57

2011-04-14 11:28:07

光纖

2009-07-15 16:14:36

iBATIS優(yōu)缺點(diǎn)

2010-05-25 16:46:00

2011-05-26 11:22:04

SEO

2009-10-10 16:33:29

綜合布線系統(tǒng)

2009-11-09 11:01:01

ibmdwPMP

2009-12-03 14:37:47

安裝phpMyAdmi

2009-06-12 09:46:40

Java String

2010-10-29 16:33:45

ORACLE存儲(chǔ)過程

2014-01-13 10:50:28

虛擬化存儲(chǔ)

2011-05-19 14:29:50

Oracle存儲(chǔ)語法

2009-10-14 11:23:20

網(wǎng)絡(luò)布線系統(tǒng)

2009-12-15 17:47:17

VSIP

2011-07-22 13:25:10

復(fù)印機(jī)租賃技巧

2015-03-11 13:54:25

云技術(shù)云應(yīng)用云存儲(chǔ)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)