詳解synchronized鎖的各種用法及注意事項(xiàng)
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í)互斥
- public class SynchronizeAndClassLock {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- // new了一個(gè)ClassLock對(duì)象
- new ClassLock().test1();
- }).start();
- new Thread(() -> {
- // new了另一個(gè)ClassLock對(duì)象
- new ClassLock().test2();
- }).start();
- }
- }
- class ClassLock {
- public synchronized static 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 static void test2(){ 不會(huì)互斥,因?yàn)榇藭r(shí)test2沒有使用類鎖。
- public synchronized static 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...");
- }
- }
運(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í)互斥
- public class SynchronizeAndClassLock2 {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- // new了一個(gè)ClassLock2對(duì)象
- new ClassLock2().test1();
- // ClassLock2.test1();
- }).start();
- new Thread(() -> {
- // new了另一個(gè)ClassLock2對(duì)象
- new ClassLock2().test2();
- // ClassLock2.test2();
- }).start();
- }
- }
- class ClassLock2 {
- public synchronized static 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 static void test2(){
- // 【注意】synchronized (SynchronizeAndClassLock2.class)不會(huì)互斥
- 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...");
- }
- }
- }
運(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í)互斥
- public class SynchronizeAndClassLock10 {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- new RunObject1().test1();
- }).start();
- new Thread(() -> {
- new RunObject2().test2();
- }).start();
- }
- }
- class RunObject1 {
- public static void test1(){
- // 【1】synchronized (StaticLock2.staticLock1) {
- synchronized (StaticLock2.staticLock) {
- 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 RunObject2 {
- public static void test2() {
- // 【2】synchronized (StaticLock2.staticLock2) {
- synchronized (StaticLock2.staticLock) {
- 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 StaticLock2 {
- 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í)互斥
- public class SynchronizeAndObjectLock2 {
- public static void main(String[] args) throws Exception {
- // 【注意】當(dāng)且僅當(dāng)是同一個(gè)SynchronizeAndObjectLock2對(duì)象
- SynchronizeAndObjectLock2 synchronizeAndObjectLock2 = new SynchronizeAndObjectLock2();
- new Thread(() -> {
- synchronizeAndObjectLock2.test1();
- }).start();
- new Thread(() -> {
- synchronizeAndObjectLock2.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...");
- }
- }
運(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í)互斥
- public class SynchronizeAndObjectLock3 {
- public static void main(String[] args) throws Exception {
- // 【注意】當(dāng)且僅當(dāng)是同一個(gè)SynchronizeAndObjectLock3對(duì)象
- SynchronizeAndObjectLock3 synchronizeAndObjectLock3 = new SynchronizeAndObjectLock3();
- new Thread(() -> {
- synchronizeAndObjectLock3.test1();
- }).start();
- new Thread(() -> {
- synchronizeAndObjectLock3.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...");
- }
- }
運(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ì)互斥
- public class SynchronizeAndObjectLock {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- // 這里new 了一個(gè)SynchronizeAndObjectLock對(duì)象
- new SynchronizeAndObjectLock().test1();
- }).start();
- new Thread(() -> {
- // 這里new 了另一個(gè)SynchronizeAndObjectLock對(duì)象
- new SynchronizeAndObjectLock().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...");
- }
- }
運(yùn)行結(jié)果:
【結(jié)論】?jī)蓚€(gè)線程同時(shí)執(zhí)行被synchronized修飾的不同對(duì)象的不同(相同)方法,鎖未生效,因?yàn)閮蓚€(gè)線程使用的是不同的對(duì)象鎖。
3.4 synchronized代碼塊修飾同一個(gè)對(duì)象時(shí)互斥
- public class SynchronizeAndObjectLock5 {
- private Object objectLock = new Object();
- public static void main(String[] args) throws Exception {
- SynchronizeAndObjectLock5 synchronizeAndObjectLock5 = new SynchronizeAndObjectLock5();
- new Thread(() -> {
- synchronizeAndObjectLock5.test1();
- }).start();
- new Thread(() -> {
- synchronizeAndObjectLock5.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...");
- }
- }
- }
運(yùn)行結(jié)果
【結(jié)論】synchronized代碼塊修飾同一個(gè)對(duì)象時(shí)互斥,若synchronized代碼塊修飾的是不同對(duì)象,那么不會(huì)互斥。
4 synchronized修飾當(dāng)前類和當(dāng)前對(duì)象時(shí)不會(huì)互斥
- public class ClassAndObjectLock {
- public static void main(String[] args) throws Exception {
- new Thread(() -> {
- ClassAndObjectLock.test1();
- }).start();
- new Thread(() -> {
- new ClassAndObjectLock().test2();
- }).start();
- }
- public static void test1(){
- synchronized (ClassAndObjectLock.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...");
- }
- }
- }
運(yùn)行結(jié)果:
【結(jié)論】可見,類鎖和對(duì)象鎖是相互獨(dú)立的,互不相斥。
5 synchronized鎖注意事項(xiàng)
5.1 synchronized鎖不能被中斷
為了模擬synchronized鎖不可中斷,下面先讓兩個(gè)線程進(jìn)入死鎖,然后再用main線程去中斷其中一個(gè)線程,看被中斷的線程能否釋放鎖并被喚醒。
- 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();
- }
- }
運(yùn)行結(jié)果:
【結(jié)論】如上圖,main線程中斷Thread-0后,Thread-0并不會(huì)釋放鎖并醒過來。同樣的,ReentrantLock的tryLock或lockInterruptibly是可以被中斷的。
5.2 synchronized鎖可重入
5.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...");
- }
- }
運(yùn)行結(jié)果:
5.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();
- }
- }
- }
運(yùn)行結(jié)果:
5.3 synchronized鎖不帶超時(shí)功能
synchronized鎖不帶超時(shí)功能,而ReentrantLock的tryLock是具備帶超時(shí)功能的,在指定時(shí)間沒獲取到鎖,該線程會(huì)蘇醒,有助于預(yù)防死鎖的產(chǎn)生。
5.4 喚醒/等待需要synchronized鎖
- public class NotifyNeedSynchronized {
- public static Object lock = new Object();
- public static void main(String[] args) throws Exception{
- // 拋出IllegalMonitorStateException
- //lock.notify();
- lock.wait();
- }
- }
運(yùn)行結(jié)果:
【結(jié)論】使用Object的notify和wait等方法時(shí),必須要使用synchronized鎖,否則會(huì)拋出IllegalMonitorStateException。
5.5 使用synchronized鎖時(shí)盡量縮小范圍以保證性能
使用synchronized鎖時(shí),為了盡可能提高性能,我們應(yīng)該盡量縮小鎖的范圍。能不鎖方法就不鎖方法,推薦盡量使用synchronized代碼塊來降低鎖的范圍。以下面的一段netty源碼為例:
- // ServerBootstrap.java
- 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;
- }
可見,找到并發(fā)訪問代碼的臨界區(qū),并不用synchronized鎖全部代碼,盡量避免使用synchronized來修飾方法。
6 總結(jié)
本文對(duì)synchronized的各種用法及注意事項(xiàng)通過demo簡(jiǎn)單梳理了下,后面有時(shí)間會(huì)探討下synchronized的原理。