Synchronized 使用详解


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并不会释放锁并醒过来。同样的,ReentrantLocktryLocklockInterruptibly是可以被中断的。

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锁不带超时功能,而ReentrantLocktryLock是具备带超时功能的,在指定时间没获取到锁,该线程会苏醒,有助于预防死锁的产生。

4 唤醒/等待需要synchronized锁

public class NotifyNeedSynchronized { public static Object lock = new Object(); public static void main(String[] args) throws Exception{ // 抛出IllegalMonitorStateException //lock.notify();
 lock.wait(); } }

运行结果:

 【结论】使用Objectnotifywait等方法时,必须要使用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来修饰方法。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM