Java 中的锁 ReentrantLock

Java juc About 1,757 words

特性

可重入、互斥(读写互斥、写写互斥、读读互斥),只能有一个线程进行操作。

默认是非公平锁,可通过构造函数指定是否是公平锁。非公平锁性能略微好一些,主要是第一个持有锁的线程解锁后,若AQS的双向链表中有等待抢锁的线程时,不从双向链表中取,而是直接给新来的抢锁线程获得。

代码示例

public class ReentrantLockDemo {
    static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {
            lock.lock();
            // 加几次放几次
            lock.lock();

            try {
                System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + "----------外层");
                lock.lock();
                try {
                    System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + "---------内层");
                } finally {
                    lock.unlock();
                }
            } finally {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.unlock();
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + "----------外层");
                lock.lock();
                try {
                    System.out.println(LocalDateTime.now() + " " + Thread.currentThread().getName() + "---------内层");
                } finally {
                    lock.unlock();
                }
            } finally {
                lock.unlock();

            }
        }, "t2").start();
    }

}

输出:

2021-03-27T20:24:26.263 t1----------外层
2021-03-27T20:24:26.263 t1---------内层
2021-03-27T20:24:29.267 t2----------外层
2021-03-27T20:24:29.268 t2---------内层
Views: 1,848 · Posted: 2021-04-07

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh