Java面試——關於synchronized與ReentrantLock的詳細區別

synchronized與ReentrantLock的區別

工作與面試中經常會遇到Java常見的加鎖方法,本文着重介紹一下synchronized與ReentrantLock的區別,總結一下目前在這方面學習到的知識。

底層實現上來說,synchronized 是JVM層面的鎖,是Java關鍵字,通過monitor對象來完成(monitorenter與monitorexit),對象只有在同步塊或同步方法中才能調用wait/notify方法,ReentrantLock 是從jdk1.5以來(java.util.concurrent.locks.Lock)提供的API層面的鎖。

synchronzied的實現涉及到鎖的升級,具體爲無鎖、偏向鎖、自旋鎖、向OS申請重量級鎖,ReentrantLock實現則是通過利用CAS(CompareAndSwap)自旋機制保證線程操作的原子性和volatile保證數據可見性以實現鎖的功能。

synchronized (new Object()){

}

new ReentrantLock();

使用javap -c對如上代碼進行反編譯得到如下代碼:
在這裏插入圖片描述

是否可手動釋放:

​ synchronized 不需要用戶去手動釋放鎖,synchronized 代碼執行完後系統會自動讓線程釋放對鎖的佔用;

​ ReentrantLock則需要用戶去手動釋放鎖,如果沒有手動釋放鎖,就可能導致死鎖現象。一般通過lock()和unlock()方法配合try/finally語句塊來完成,使用釋放更加靈活。

private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private AtomicInteger atomicInteger;

    public void increment() throws Exception {
        lock.lock();
        try {

            while (number != 0) {
                condition.await();
            }
            //do something
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

是否可中斷

​ synchronized是不可中斷類型的鎖,除非加鎖的代碼中出現異常或正常執行完成;

​ ReentrantLock則可以中斷,可通過trylock(long timeout,TimeUnit unit)設置超時方法或者將lockInterruptibly()放到代碼塊中,調用interrupt方法進行中斷。

    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

是否公平鎖

​ synchronized爲非公平鎖

​ ReentrantLock則即可以選公平鎖也可以選非公平鎖,通過構造方法new ReentrantLock時傳入boolean值進行選擇,爲空默認false非公平鎖,true爲公平鎖。

    /**
     * Creates an instance of {@code ReentrantLock}.
     * This is equivalent to using {@code ReentrantLock(false)}.
     */
    public ReentrantLock() {
        sync = new NonfairSync();
    }

    /**
     * Creates an instance of {@code ReentrantLock} with the
     * given fairness policy.
     *
     * @param fair {@code true} if this lock should use a fair ordering policy
     */
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

鎖是否可綁定條件Condition

​ synchronized不能綁定;

​ ReentrantLock通過綁定Condition結合await()/singal()方法實現線程的精確喚醒,而不是像synchronized通過Object類的wait()/notify()/notifyAll()方法要麼隨機喚醒一個線程要麼喚醒全部線程。

​ 示例:用ReentrantLock綁定三個條件實現線程A打印一次1,線程B打印兩次2,線程C打印三次3

class Resource {
    private int number = 1;//A:1  B:2  C:3
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    //1 判斷
    public void print1() {

        lock.lock();

        try {
            //判斷
            while (number != 1) {
                c1.await();
            }
            //2 do sth
            for (int i = 1; i < 2; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + number);
            }

            //3 通知
            number = 2;
            c2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //1 判斷
    public void print2() {

        lock.lock();

        try {
            //判斷
            while (number != 2) {
                c2.await();
            }
            //2 do sth
            for (int i = 1; i < 3; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + number);
            }

            //3 通知
            number = 3;
            c3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //1 判斷
    public void print3() {

        lock.lock();

        try {
            //判斷
            while (number != 3) {
                c3.await();
            }
            //2 do sth
            for (int i = 1; i < 4; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + number);
            }

            //3 通知
            number = 1;
            c1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public static void main(String[] args) {

        Resource resource = new Resource();

        new Thread(()->{
            for (int i = 1; i <= 2; i++) {
                resource.print1();
            }
        },"A").start();


        new Thread(()->{
            for (int i = 1; i <= 2; i++) {
                resource.print2();
            }
        },"B").start();


        new Thread(()->{
            for (int i = 1; i <= 2; i++) {
                resource.print3();
            }
        },"C").start();


    }

輸出結果爲:

A 1
B 2
B 2
C 3
C 3
C 3
A 1
B 2
B 2
C 3
C 3
C 3

鎖的對象

synchronzied鎖的是對象,鎖是保存在對象頭裏面的,根據對象頭數據來標識是否有線程獲得鎖/爭搶鎖;ReentrantLock鎖的是線程,根據進入的線程和int類型的state標識鎖的獲得/爭搶。

完!如有不妥,歡迎批評指正!

發佈了35 篇原創文章 · 獲贊 13 · 訪問量 8521
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章