Java ReentrantLock 詳解

ReentrantLock 和 synchronized 的區別:

1.ReentrantLock 不需要代碼塊,在開始的時候lock,在結束的時候unlock 就可以了。

但是要注意,lock 是有次數的,如果連續調用了兩次lock,那麼就需要調用兩次unlock。否則的話,別的線程是拿不到鎖的。

    /**
     * 很平常的用鎖 沒有感覺reentrantlocak 的強大
     *
     * 如果當前線程已經拿到一個鎖了 那麼再次調用 會裏面返回true
     * 當前線程的鎖數量是 2個
     *
    */
    private void normalUse() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        new Thread("thread1"){
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG,"thread1 lock");
                reentrantLock.lock();
                reentrantLock.lock();
               
                LogToFile.log(TAG,"thread1 getHoldCount:"  + reentrantLock.getHoldCount() );

                try {
                    LogToFile.log(TAG,"thread1 run");

                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                 //如果說你的線程佔了兩個鎖 一個沒有釋放 其他線程都拿不到這個鎖
                 //上面lock 了兩次 這裏需要unLock 兩次
                reentrantLock.unlock();
                reentrantLock.unlock();
                LogToFile.log(TAG,"thread1 unlock");
            }
        }.start();


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 lock");
                reentrantLock.lock();
                LogToFile.log(TAG,"thread2 run");

                reentrantLock.unlock();
                LogToFile.log(TAG,"thread2 unlock");

            }
        }.start();
    }

ReentrantLock trylock()

ReentrantLock trylock 會嘗試去拿鎖,如果拿得到,就返回true, 如果拿不到就返回false.這個都是立馬返回,不會阻塞線程。
如果當前線程已經拿到鎖了,那麼trylock 會返回true.

    /**
     * trylock 不管能不能拿到鎖 都會裏面返回結果 而不是等待
     * tryLock 會破壞ReentrantLock 的 公平機制
     * 注意 如果沒有拿到鎖 執行完代碼之後不要釋放鎖,
     * 否則會有exception
     *
     */
    private void UseTryLock() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        new Thread("thread1"){
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG,"thread1 lock");
                reentrantLock.lock();
                try {
                    LogToFile.log(TAG,"thread1 run");

                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.unlock();
                LogToFile.log(TAG,"thread1 unlock");
            }
        }.start();


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 tryLock");
                boolean success = reentrantLock.tryLock();
                LogToFile.log(TAG,"thread2 run");

                if (success) {
                    reentrantLock.unlock();
                    LogToFile.log(TAG,"thread2 unlock");
                    //    java.lang.IllegalMonitorStateException
                    //        at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:123)
                    //        at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1235)
                    //        at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:429)

                }

            }
        }.start();
    }

ReentrantLock .tryLock(5, TimeUnit.SECONDS)

ReentrantLock 可以指定,嘗試去獲取鎖,等待多長時間之後,如果還獲取不到,那麼就放棄。

    /**
     * tryLock(5, TimeUnit.SECONDS)
     * 如果5s之後 還拿不到鎖  那麼就不再堵塞線程,也不去拿鎖了 執行執行下面的代碼了
     */
    private void UseTryLockWhitTime() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        new Thread("thread1"){
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG,"thread1 lock");
                reentrantLock.lock();
                try {
                    LogToFile.log(TAG,"thread1 run");

                    Thread.sleep(1000 * 10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.unlock();
                LogToFile.log(TAG,"thread1 unlock");
            }
        }.start();


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 tryLock");
                boolean success = false;
                try {
                    success = reentrantLock.tryLock(5, TimeUnit.SECONDS);
                    LogToFile.log(TAG,"thread2 run");

                    if (success) {
                        reentrantLock.unlock();
                        LogToFile.log(TAG,"thread2 unlock");
                        //    java.lang.IllegalMonitorStateException
                        //        at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:123)
                        //        at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1235)
                        //        at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:429)

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

ReentrantLock .lock();

一旦調用了ReentrantLock .lock() ,如果你的線程被其他線程interrupt,那麼你的線程並不會interrupt,而是繼續等待鎖。

    /**
     * lockInterruptibly() 和  lock 的區別是
     * 如果當前線程被Interrupt 了,那麼lockInterruptibly 就不再等待鎖了。直接會拋出來一個異常給你處理
     * 如果是lock 的話 就算 線程被其他的線程lockInterrupt 了,不管用,他還會繼續等待鎖
     */
    private void UseLockIntercepter() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        Thread thread = new Thread("thread1") {
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG, "thread1 lock");
                reentrantLock.lock();
                LogToFile.log(TAG, "thread1 run");
                if (reentrantLock.getHoldCount() != 0) {
                    reentrantLock.unlock();
                }
                LogToFile.log(TAG, "thread1 unlock");
            }
        };


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 tryLock");
                boolean success = false;
                try {
                    reentrantLock.lock();
                    thread.start();

                    thread.interrupt();
                    success = reentrantLock.tryLock(5, TimeUnit.SECONDS);
                    LogToFile.log(TAG,"thread2 run");

                    if (success) {
                        reentrantLock.unlock();
                        reentrantLock.unlock();
                        LogToFile.log(TAG,"thread2 unlock");
                        //    java.lang.IllegalMonitorStateException
                        //        at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:123)
                        //        at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1235)
                        //        at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:429)

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

ReentrantLock .lockInterruptibly();

如果當前線程調用lockInterruptibly 這個方法去獲取鎖,當其他的線程把你的線程給interrupt 之後,那麼你的線程就不再等待鎖了,執行下面的代碼。

    /**
     * lockInterruptibly() 和  lock 的區別是
     * 如果當前線程被Interrupt 了,那麼lockInterruptibly 就不再等待鎖了。直接會拋出來一個異常給你處理
     * 如果是lock 的話 就算 線程被其他的線程lockInterrupt 了,不管用,他還會繼續等待鎖
     */
    private void UseLockIntercepter2() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        Thread thread = new Thread("thread1") {
            @Override
            public void run() {
                super.run();
                LogToFile.log(TAG, "thread1 lock");
                try {
                    reentrantLock.lockInterruptibly();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    LogToFile.log(TAG, "thread1 lock InterruptedException ");

                }
                LogToFile.log(TAG, "thread1 run");
                if (reentrantLock.getHoldCount() != 0) {
                    reentrantLock.unlock();
                }
                LogToFile.log(TAG, "thread1 unlock");
            }
        };


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();

                LogToFile.log(TAG,"thread2 tryLock");
                boolean success = false;
                try {
                    reentrantLock.lock();
                    thread.start();

                    thread.interrupt();
                    success = reentrantLock.tryLock(5, TimeUnit.SECONDS);
                    LogToFile.log(TAG,"thread2 run");

                    if (success) {
                        reentrantLock.unlock();
                        reentrantLock.unlock();
                        LogToFile.log(TAG,"thread2 unlock");
                        //    java.lang.IllegalMonitorStateException
                        //        at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:123)
                        //        at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1235)
                        //        at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:429)

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

ReentrantLock newCondition()使用:

condition. 的await 相當於 object 的wait 方法,就是等待其他線程喚醒,但是調用之前必須要reentrantLock.lock(); 一下,不然會拋異常。

    /**
     * tryLock(5, TimeUnit.SECONDS)
     * 如果5s之後 還拿不到鎖  那麼就不再堵塞線程,也不去拿鎖了 執行執行下面的代碼了
     */
    private void UseCondition() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        Condition condition = reentrantLock.newCondition();
        Thread thread = new Thread("thread1") {
            @Override
            public void run() {
                super.run();

                try {
                    reentrantLock.lock();
                    LogToFile.log(TAG, "thread1 wait");
                    //await 其實是會釋放鎖的 其他的線程可以拿到鎖 然後signal  不然的話豈不是要卡死?
                    condition.await();

                    LogToFile.log(TAG, "thread1 run");

                    Thread.sleep(1000 * 3);
                    condition.signalAll();
                    reentrantLock.unlock();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LogToFile.log(TAG, "thread1 unlock");
            }
        };
        thread.start();


        Thread thread1 = new Thread("thread2") {
            @Override
            public void run() {
                super.run();
                //調用signal 之前一定要lock
                reentrantLock.lock();
                //就算沒有人調用await 那麼signal 方法也不會有什麼問題
                condition.signal();

                try {
                    LogToFile.log(TAG, "thread2 wait");
                    condition.await();
                    LogToFile.log(TAG, "thread2 run");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                reentrantLock.unlock();
            }
        };
        thread1.start();
    }

Object wait方法使用:

wait 方法調用之前也要synchronized 一個鎖。

    /**
     * 使用wait
     */
    private void UseWait() {
        ReentrantLock reentrantLock =  new ReentrantLock();
        Condition condition = reentrantLock.newCondition();
        new Thread("thread1"){
            @Override
            public void run() {
                super.run();

                try {
                    synchronized (condition) {
                        LogToFile.log(TAG,"thread1 wait");
                        condition.wait();
                    }

                    LogToFile.log(TAG,"thread1 run");

                    Thread.sleep(1000 * 10);
                    synchronized (condition) {
                        condition.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LogToFile.log(TAG,"thread1 unlock");
            }
        }.start();


        new Thread("thread2"){
            @Override
            public void run() {
                super.run();
                synchronized (condition) {
                    condition.notify();

                }
                try {
                    LogToFile.log(TAG,"thread2 wait");
                    synchronized (condition){
                        condition.wait();
                    }
                    LogToFile.log(TAG,"thread2 run");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

synchronized

synchronized 鎖等待的線程,當被其他線程interrupt 的時候,並不會停止。

/**
 * synchronized 的鎖,不能被中斷
 */
public void testSyncInter(){
    Object lock = new Object();
    Thread thread = new Thread("thread1") {
        @Override
        public void run() {
            super.run();
            synchronized (lock) {
                LogToFile.log(TAG, "thread1 lock");
                LogToFile.log(TAG, "thread1 run");
            }
            LogToFile.log(TAG, "thread1 unlock");

        }
    };


    new Thread("thread2"){
        @Override
        public void run() {
            super.run();
            synchronized (lock) {
                LogToFile.log(TAG,"thread2 start");
                thread.start();
                thread.interrupt();

            }
            LogToFile.log(TAG,"thread2 run");
        }
    }.start();
}

BlockingQueue 就是使用ReentrantLock 實現的阻塞隊列:

    /**
     * BlockingQueue  會阻塞當前的線程  等着其他線程放數據
     */
    public void testArrayBlockQueue(){
        BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(4);

        new Thread("thread1"){
            @Override
            public void run() {
                super.run();
                try {
                    LogToFile.log(TAG,"thread1 take");
                    blockingQueue.take();
                    LogToFile.log(TAG,"thread1 take  get");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread("thread2"){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    LogToFile.log(TAG,"thread2 put");

                    //put 會阻塞 但是add 不會
                    blockingQueue.put(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

ArrayBlockingQueue 源碼解析:

下面的代碼,可以看到ArrayBlockingQueue 創建了ReentrantLock ,以及兩個condition


    /** Main lock guarding all access */
    final ReentrantLock lock;

    /** Condition for waiting takes */
    private final Condition notEmpty;

    /** Condition for waiting puts */
    private final Condition notFull;

public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }

當我們往裏面放元素的時候,我們會對notFull 進行等待,因爲隊列不是空的了。

當出隊列的時候,notFull.signal(); 也就是當前的隊列不是滿的了,可以放元素進去了。

    /**
     * Inserts the specified element at the tail of this queue, waiting
     * for space to become available if the queue is full.
     *
     * @throws InterruptedException {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

    private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;
    }

當我們往裏面取元素的時候,如果隊列是空的了,那麼notEmpty 就要等待,當enqueue一個元素的時候,notEmpty 不是空就喚醒,那麼take 就可以執行去拿元素了。

    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章