Synchronized 使用詳解
1、簡介
Synchronized
鎖是jvm內置的鎖,不同於ReentrantLock
鎖。synchronized
關鍵字可以修飾方法,也可以修飾代碼塊。synchronized
關鍵字修飾方法時可以修飾靜態方法,也可以修飾非靜態方法;同樣,synchronized
關鍵字修飾代碼塊時可以修飾對象,也可以修飾類。當然,synchronized
修飾靜態方法/類和非靜態方法/對象時的作用范圍是不同的。下面通過各種demo
來詳解synchronized
的各種用法及注意事項。
2、測試demo
1、synchronized類鎖
這里所說的 synchronized
類鎖的作用范圍是類級別的,不會因為同一個類的不同對象執行而失效。
結論: 1.1、 synchronized修飾同一個類的兩個靜態方法時互斥。
public class TestClassLock { public static void main(String[] args) throws Exception { new Thread(() -> { ClassLock.test1(); }).start(); new Thread(() -> { ClassLock.test2(); }).start(); } } class ClassLock { public synchronized static void test1(){ System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(2); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } // 【注意】public static void test2(){ 不會互斥,因為此時test2沒有使用類鎖。
public synchronized static void test2(){ System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(2); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } }
執行結果:
test2
方法如果沒有synchronized
修飾的話,執行結果如下:
【結論】兩個線程分別同時執行同一個類產生的不同對象的兩個不同 synchronized static
方法,類鎖生效,雖然是不同對象,因為兩個線程使用的是同一個類鎖。反過來,假如test2
方法沒有synchronized
修飾的話,只有test1
方法有被synchronized
修飾,此時兩個方法也不會互斥,一個有鎖,一個沒有鎖,自然不會互斥。
結論:1.2、 synchronized分別修飾同一個類的靜態方法和代碼塊中使用類鎖時互斥
public class Test2ClassLock { public static void main(String[] args) throws Exception { new Thread(() -> { ClassLock2.test1(); }).start(); new Thread(() -> { ClassLock2.test2(); }).start(); } } class ClassLock2 { public synchronized static void test1(){ System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(2); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } public static void test2(){ // 【注意】synchronized (OtherClass.class)不會互斥
synchronized (ClassLock2.class) { System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } } }
執行結果:
【結論】兩個線程同時分別執行一個被synchronized修飾static方法,一個有synchnized(該類)代碼塊的static方法,鎖生效,雖然是不同對象,因為兩個線程使用的同一個類鎖。反過來,如果是修飾的不同類,因為類鎖不同,肯定不會互斥,比如將test2
方法的synchronized (ClassLock2.class)
這句代碼改成synchronized (OtherClass.class)
,此時不會互斥。
結論:1.3、 synchronized分別修飾同一個靜態對象時互斥
public class Test3ClassLock { public static void main(String[] args) throws Exception { new Thread(() -> { ClassLock3.test1(); }).start(); new Thread(() -> { ClassLock4.test2(); }).start(); } } class ClassLock3 { public static void test1(){ // 【1】synchronized (StaticLock.staticLock1) {
synchronized (StaticLock.staticLock1) { System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } } } class ClassLock4 { public static void test2() { // 【2】synchronized (StaticLock.staticLock2) {
synchronized (StaticLock.staticLock1) { System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } } } class StaticLock { public static final Object staticLock1 = new Object(); public static final Object staticLock2 = new Object(); }
【結論】synchronized
分別修飾同一個類的靜態對象時互斥,反過來,如果是修飾不同的靜態對象,肯定不會互斥,比如將上面代碼中標【1】
和【2】
的synchronized
代碼結合使用。
2、synchronized對象鎖
這里說的synchronized
對象鎖的作用范圍是對象級別的即僅僅作用於同一個對象,如果是同一個類的兩個不同的對象是不會互斥的,即沒有效果的。
2.1、 synchronized修飾同一個類對象的兩個非靜態方法時互斥
public class TestObjectLock { public static void main(String[] args) throws Exception { // 【注意】當且僅當是同一個SynchronizeAndObjectLock2對象
TestObjectLock testObjectLock = new TestObjectLock(); new Thread(() -> { testObjectLock.test1(); }).start(); new Thread(() -> { testObjectLock.test2(); }).start(); } public synchronized void test1(){ System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } public synchronized void test2(){ System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } }
運行結果:
【結論】兩個線程同時執行被synchronized
修飾的相同對象的不同(相同)方法,鎖生效,因為兩個線程使用的是相同的對象鎖。
2.2、synchronized分別修飾同一個類對象的非靜態方法和當前對象時互斥
public class Test2ObjectLock { public static void main(String[] args) throws Exception { // 【注意】當且僅當是同一個SynchronizeAndObjectLock3對象
Test2ObjectLock test2ObjectLock = new Test2ObjectLock(); new Thread(() -> { test2ObjectLock.test1(); }).start(); new Thread(() -> { test2ObjectLock.test2(); }).start(); } public void test1(){ synchronized(this) { System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } } public synchronized void test2(){ System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } }
運行結果:
【結論】synchronized
修飾非靜態方法與synchronized(this)
互斥,可見,snchronized
修飾非靜態方法實質鎖的是當前對象。
2.3、 synchronized修飾不同對象的兩個非靜態方法時不會互斥
public class Test3ObjectLock { public static void main(String[] args) throws Exception { new Thread(() -> { // 這里new 了一個Test3ObjectLock對象
new Test3ObjectLock().test1(); }).start(); new Thread(() -> { // 這里new 了另一個Test3ObjectLock對象
new Test3ObjectLock().test2(); }).start(); } public synchronized void test1(){ System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } public synchronized void test2(){ System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } }
執行結果:
【結論】兩個線程同時執行被synchronized
修飾的不同對象的不同(相同)方法,鎖未生效,因為兩個線程使用的是不同的對象鎖。
2.4、 synchronized代碼塊修飾同一個對象時互斥
public class Test4ObjectLock { private final Object objectLock = new Object(); public static void main(String[] args) throws Exception { Test4ObjectLock test4ObjectLock = new Test4ObjectLock(); new Thread(() -> { test4ObjectLock.test1(); }).start(); new Thread(() -> { test4ObjectLock.test2(); }).start(); } public void test1(){ synchronized(objectLock) { System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } } public void test2(){ synchronized(objectLock) { System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } } }
運行結果:
【結論】synchronized
代碼塊修飾同一個對象時互斥,若synchronized
代碼塊修飾的是不同對象,那么不會互斥。
3、synchronized修飾當前類和當前對象時不會互斥
public class TestClassAndObjectLock { public static void main(String[] args) throws Exception { new Thread(() -> { TestClassAndObjectLock.test1(); }).start(); new Thread(() -> { new TestClassAndObjectLock().test2(); }).start(); } public static void test1(){ synchronized (TestClassAndObjectLock.class) { System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } } public void test2(){ synchronized (this) { System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) {} System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); } } }
運行結果:
【結論】可見,類鎖和對象鎖是相互獨立的,互不相斥。
3、synchronized鎖注意事項
1、synchronized鎖不能被中斷
為了模擬synchronized
鎖不可中斷,下面先讓兩個線程進入死鎖,然后再用main
線程去中斷其中一個線程,看被中斷的線程能否釋放鎖並被喚醒。
public class DeadLockCannotInterruptDemo { private static Object lock1 = new Object(); private static Object lock2 = new Object(); public static void main(String[] args) throws Exception { Thread threadA = new Thread(new Runnable() { @Override public void run() { synchronized (lock1) { System.out.println(Thread.currentThread().getName() + " get lock1"); try { Thread.sleep(10); synchronized (lock2) { System.out.println(Thread.currentThread().getName() + " get lock2"); } } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread threadB = new Thread(new Runnable() { @Override public void run() { synchronized (lock2) { System.out.println(Thread.currentThread().getName() + " get lock2"); try { Thread.sleep(10); synchronized (lock1) { System.out.println(Thread.currentThread().getName() + " get lock1"); } } catch (InterruptedException e) { e.printStackTrace(); } } } }); threadA.start(); threadB.start(); TimeUnit.SECONDS.sleep(3); System.out.println("main thread begin to interrupt " + threadA.getName() + " and " + threadA.getName() + " will release lock1..."); threadA.interrupt(); } }
運行結果:
【結論】如上圖,main
線程中斷Thread-0
后,Thread-0
並不會釋放鎖並醒過來。同樣的,ReentrantLock
的tryLock
或lockInterruptibly
是可以被中斷的。
2 、synchronized鎖可重入
2.1、不同方法,synchronized是可重入的
public class SynchronizeAndReentrant { public static void main(String[] args) throws Exception { SynchronizeAndReentrant synchronizeAndReentrant = new SynchronizeAndReentrant(); synchronizeAndReentrant.test1(); } public synchronized void test1(){ System.out.println(" test1 method is called..."); test2(); } public synchronized void test2(){ System.out.println(" test2 method is called..."); } }
運行結果:
2.2 、相同方法,synchronized是可重入的
public class SynchronizeAndReentrant2 { int i = 1; public static void main(String[] args) throws Exception { SynchronizeAndReentrant2 synchronizeAndReentrant = new SynchronizeAndReentrant2(); synchronizeAndReentrant.test1(); } public synchronized void test1(){ System.out.println(" test1 method is called " + i++ + "st time..." ); while(i < 5) { test1(); } } }
運行結果:
3、 synchronized鎖不帶超時功能
synchronized
鎖不帶超時功能,而ReentrantLock
的tryLock
是具備帶超時功能的,在指定時間沒獲取到鎖,該線程會蘇醒,有助於預防死鎖的產生。
4 喚醒/等待需要synchronized鎖
public class NotifyNeedSynchronized { public static Object lock = new Object(); public static void main(String[] args) throws Exception{ // 拋出IllegalMonitorStateException //lock.notify();
lock.wait(); } }
運行結果:
【結論】使用Object
的notify
和wait
等方法時,必須要使用synchronized
鎖,否則會拋出IllegalMonitorStateException
。
5 、使用synchronized鎖時盡量縮小范圍以保證性能
使用synchronized
鎖時,為了盡可能提高性能,我們應該盡量縮小鎖的范圍。能不鎖方法就不鎖方法,推薦盡量使用synchronized
代碼塊來降低鎖的范圍。以下面的一段netty
源碼為例:
public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value) { if (childOption == null) { throw new NullPointerException("childOption"); } if (value == null) { synchronized (childOptions) { childOptions.remove(childOption); } } else { synchronized (childOptions) { childOptions.put(childOption, value); } } return this; }
可見,找到並發訪問代碼的臨界區,並不用synchronized
鎖全部代碼,盡量避免使用synchronized
來修飾方法。