详解synchronized锁的各种用法及注意事项

开发 后端
本文主要通过简单的demo来阐述synchronized锁的各种用法以及使用synchronized锁的相关注意事项,记录下来同时也方便自己记忆。

 [[440304]]

1 前言

本文主要通过简单的demo来阐述synchronized锁的各种用法以及使用synchronized锁的相关注意事项,记录下来同时也方便自己记忆。

synchronized锁是jvm内置的锁,不同于ReentrantLock锁。synchronized关键字可以修饰方法,也可以修饰代码块。synchronized关键字修饰方法时可以修饰静态方法,也可以修饰非静态方法;同样,synchronized关键字修饰代码块时可以修饰对象,也可以修饰类。当然,synchronized修饰静态方法/类和非静态方法/对象时的作用范围是不同的。下面通过各种demo来详解synchronized的各种用法及注意事项。

2 synchronized类锁

这里所说的synchronized类锁的作用范围是类级别的,不会因为同一个类的不同对象执行而失效。

2.1 synchronized修饰同一个类的两个静态方法时互斥 

  1. public class SynchronizeAndClassLock {  
  2.     public static void main(String[] args) throws Exception {  
  3.         new Thread(() -> {  
  4.             // new了一个ClassLock对象  
  5.             new ClassLock().test1();  
  6.         }).start();  
  7.         new Thread(() -> {  
  8.             // new了另一个ClassLock对象  
  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(){ 不会互斥,因为此时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.     }  

运行结果:

【结论】两个线程分别同时执行同一个类产生的不同对象的两个不同 synchronized static方法,类锁生效,虽然是不同对象,因为两个线程使用的是同一个类锁。反过来,假如test2方法没有synchronized修饰的话,只有test1方法有被synchronized修饰,此时两个方法也不会互斥,一个有锁,一个没有锁,自然不会互斥。

2.2 synchronized分别修饰同一个类的静态方法和当前类时互斥 

  1. public class SynchronizeAndClassLock2 {  
  2.     public static void main(String[] args) throws Exception {  
  3.         new Thread(() -> {  
  4.             // new了一个ClassLock2对象  
  5.             new ClassLock2().test1();  
  6.             // ClassLock2.test1(); 
  7.         }).start();  
  8.         new Thread(() -> {  
  9.             // new了另一个ClassLock2对象  
  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)不会互斥  
  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.     }  

运行结果:

【结论】两个线程同时分别执行一个被synchronized修饰static方法,一个有synchnized(该类)代码块的static方法,锁生效,虽然是不同对象,因为两个线程使用的同一个类锁。反过来,如果是修饰的不同类,因为类锁不同,肯定不会互斥,比如将test2方法的synchronized (ClassLock2.class)这句代码改成synchronized (SynchronizeAndClassLock2.class),此时不会互斥。

2.3 synchronized分别修饰同一个静态对象时互斥 

  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();  

运行结果:

【结论】synchronized分别修饰同一个类的静态对象时互斥,反过来,如果是修饰不同的静态对象,肯定不会互斥,比如将上面代码中标【1】和【2】的synchronized代码结合使用。

3 synchronized对象锁

这里说的synchronized对象锁的作用范围是对象级别的即仅仅作用于同一个对象,如果是同一个类的两个不同的对象是不会互斥的,即没有效果的。

3.1 synchronized修饰同一个类对象的两个非静态方法时互斥 

  1. public class SynchronizeAndObjectLock2 {  
  2.     public static void main(String[] args) throws Exception {  
  3.         // 【注意】当且仅当是同一个SynchronizeAndObjectLock2对象  
  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.     }  

运行结果:

【结论】两个线程同时执行被synchronized修饰的相同对象的不同(相同)方法,锁生效,因为两个线程使用的是相同的对象锁

3.2 synchronized分别修饰同一个类对象的非静态方法和当前对象时互斥 

  1. public class SynchronizeAndObjectLock3 {  
  2.     public static void main(String[] args) throws Exception {  
  3.         // 【注意】当且仅当是同一个SynchronizeAndObjectLock3对象  
  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.  

运行结果:

【结论】snchronized修饰非静态方法与synchronized(this)互斥,可见,snchronized修饰非静态方法实质锁的是当前对象。

3.3 synchronized修饰不同对象的两个非静态方法时不会互斥 

  1. public class SynchronizeAndObjectLock {  
  2.     public static void main(String[] args) throws Exception {  
  3.         new Thread(() -> {  
  4.             // 这里new 了一个SynchronizeAndObjectLock对象  
  5.             new SynchronizeAndObjectLock().test1();  
  6.         }).start();  
  7.         new Thread(() -> {  
  8.             // 这里new 了另一个SynchronizeAndObjectLock对象  
  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.     }  

运行结果:

【结论】两个线程同时执行被synchronized修饰的不同对象的不同(相同)方法,锁未生效,因为两个线程使用的是不同的对象锁。

3.4 synchronized代码块修饰同一个对象时互斥 

  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.     }  

运行结果

【结论】synchronized代码块修饰同一个对象时互斥,若synchronized代码块修饰的是不同对象,那么不会互斥。

4 synchronized修饰当前类和当前对象时不会互斥 

  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.     }  

运行结果:

【结论】可见,类锁和对象锁是相互独立的,互不相斥。

5 synchronized锁注意事项

5.1 synchronized锁不能被中断

为了模拟synchronized锁不可中断,下面先让两个线程进入死锁,然后再用main线程去中断其中一个线程,看被中断的线程能否释放锁并被唤醒。 

  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.     } 

运行结果:

【结论】如上图,main线程中断Thread-0后,Thread-0并不会释放锁并醒过来。同样的,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.     }  

运行结果:

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.     }  

运行结果:

5.3 synchronized锁不带超时功能

synchronized锁不带超时功能,而ReentrantLock的tryLock是具备带超时功能的,在指定时间没获取到锁,该线程会苏醒,有助于预防死锁的产生。

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.     }  

运行结果:

【结论】使用Object的notify和wait等方法时,必须要使用synchronized锁,否则会抛出IllegalMonitorStateException。

5.5 使用synchronized锁时尽量缩小范围以保证性能

使用synchronized锁时,为了尽可能提高性能,我们应该尽量缩小锁的范围。能不锁方法就不锁方法,推荐尽量使用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;  

可见,找到并发访问代码的临界区,并不用synchronized锁全部代码,尽量避免使用synchronized来修饰方法。

6 总结

本文对synchronized的各种用法及注意事项通过demo简单梳理了下,后面有时间会探讨下synchronized的原理。 

 

责任编辑:庞桂玉 来源: Java知音
相关推荐

2021-02-07 07:40:31

Synchronize用法

2010-06-10 13:11:23

2011-06-23 11:15:25

SEO网站优化

2011-11-23 09:02:57

2009-10-22 14:07:15

布线施工注意事项

2010-05-25 16:46:00

2009-07-15 16:14:36

iBATIS优缺点

2009-10-10 16:33:29

综合布线系统

2011-05-26 11:22:04

SEO

2009-11-09 11:01:01

ibmdwPMP

2011-04-14 11:28:07

光纤

2011-05-19 14:29:50

Oracle存储语法

2009-12-03 14:37:47

安装phpMyAdmi

2010-10-29 16:33:45

ORACLE存储过程

2009-06-12 09:46:40

Java String

2011-07-22 13:25:10

复印机租赁技巧

2014-01-13 10:50:28

虚拟化存储

2010-08-09 09:05:41

DB2快照函数

2011-03-22 08:56:30

2009-10-14 11:23:20

网络布线系统
点赞
收藏

51CTO技术栈公众号