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

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

[[381155]]

本文转载自微信公众号「源码笔记」,作者 源码笔记 。转载本文请联系源码笔记公众号。

 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.  
  8.         new Thread(() -> { 
  9.             // new了另一个ClassLock对象 
  10.             new ClassLock().test2(); 
  11.         }).start(); 
  12.     } 
  13.  
  14. class ClassLock { 
  15.     public synchronized static void test1(){ 
  16.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); 
  17.         try { 
  18.             TimeUnit.SECONDS.sleep(1); 
  19.         } catch (Exception e) {} 
  20.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); 
  21.     } 
  22.  // 【注意】public static void test2(){ 不会互斥,因为此时test2没有使用类锁。 
  23.     public synchronized static void test2(){ 
  24.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); 
  25.         try { 
  26.             TimeUnit.SECONDS.sleep(1); 
  27.         } catch (Exception e) {} 
  28.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); 
  29.     } 

运行结果:

【结论】两个线程分别同时执行同一个类产生的不同对象的两个不同 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.  
  9.         new Thread(() -> { 
  10.             // new了另一个ClassLock2对象 
  11.             new ClassLock2().test2(); 
  12.             // ClassLock2.test2(); 
  13.         }).start(); 
  14.     } 
  15.  
  16. class ClassLock2 { 
  17.     public synchronized static void test1(){ 
  18.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); 
  19.         try { 
  20.             TimeUnit.SECONDS.sleep(1); 
  21.         } catch (Exception e) {} 
  22.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); 
  23.     } 
  24.  
  25.     public static void test2(){ 
  26.      // 【注意】synchronized (SynchronizeAndClassLock2.class)不会互斥 
  27.         synchronized (ClassLock2.class) { 
  28.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); 
  29.             try { 
  30.                 TimeUnit.SECONDS.sleep(1); 
  31.             } catch (Exception e) {} 
  32.             System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); 
  33.         } 
  34.     } 

运行结果:

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

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

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

运行结果:

【结论】两个线程同时执行被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.  
  9.         new Thread(() -> { 
  10.             synchronizeAndObjectLock3.test2(); 
  11.         }).start(); 
  12.     } 
  13.     public void test1(){ 
  14.         synchronized(this) { 
  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.  
  24.     public synchronized void test2(){ 
  25.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " begin..."); 
  26.         try { 
  27.             TimeUnit.SECONDS.sleep(1); 
  28.         } catch (Exception e) {} 
  29.         System.out.println(new Date() + " " + Thread.currentThread().getName() + " end..."); 
  30.     } 

运行结果:

【结论】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.  
  8.         new Thread(() -> { 
  9.             // 这里new 了另一个SynchronizeAndObjectLock对象 
  10.             new SynchronizeAndObjectLock().test2(); 
  11.         }).start(); 
  12.     } 
  13.     public synchronized void test1(){ 
  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.     } 

运行结果:

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

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

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

运行结果:

【结论】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.  
  7.         new Thread(() -> { 
  8.             new ClassAndObjectLock().test2(); 
  9.         }).start(); 
  10.     } 
  11.     public static void test1(){ 
  12.         synchronized (ClassAndObjectLock.class) { 
  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.     } 
  20.  
  21.     public void test2(){ 
  22.         synchronized (this) { 
  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.     } 

运行结果:

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

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

运行结果:

【结论】如上图,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.  
  11.     public synchronized void test2(){ 
  12.         System.out.println(" test2 method is called..."); 
  13.     } 

运行结果:

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.  
  9.         System.out.println(" test1 method is called " + i++ + "st time..." ); 
  10.         while(i < 5) { 
  11.             test1(); 
  12.         } 
  13.     } 

运行结果:

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

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

6 总结

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

 

责任编辑:武晓燕 来源: 源码笔记
相关推荐

2021-12-14 14:50:12

synchronizeJava

2011-06-23 11:15:25

SEO网站优化

2010-06-10 13:11:23

2009-10-22 14:07:15

布线施工注意事项

2011-11-23 09:02:57

2010-05-25 16:46:00

2009-07-15 16:14:36

iBATIS优缺点

2011-05-26 11:22:04

SEO

2009-10-10 16:33:29

综合布线系统

2011-04-14 11:28:07

光纤

2009-11-09 11:01:01

ibmdwPMP

2009-12-03 14:37:47

安装phpMyAdmi

2010-10-29 16:33:45

ORACLE存储过程

2009-06-12 09:46:40

Java String

2011-05-19 14:29:50

Oracle存储语法

2014-01-13 10:50:28

虚拟化存储

2011-07-22 13:25:10

复印机租赁技巧

2010-08-09 09:05:41

DB2快照函数

2009-10-14 11:23:20

网络布线系统

2011-03-22 08:56:30

点赞
收藏

51CTO技术栈公众号