简单聊聊 Java ReentrantLock

大家好,这次我们来聊聊Java线程中ReentrantLock的使用,ReentrantLock和synchronized有相同的作用,都可以保证线程的安全性,但是ReentrantLock的功能更加的强大,费话不多少,下面我们正式开始。


ReentrantLock

我们先来介绍这篇文章的的一个关键类ReentrantLock,先看看是如何使用的:

public class LockTool {

    private ReentrantLock lock = new ReentrantLock();

    public void test() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " in test");
            Thread.sleep(2000);
            lock.unlock();
            System.out.println(Thread.currentThread().getName() + " out test");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class lockmain {

    public static void main(String[] args) {

        LockTool tool = new LockTool();
        for (int i = 0; i < 5; i++) {
            ThreadA threadA = new ThreadA(tool);
            threadA.start();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }
}

结果为:

Thread-0 in test
Thread-0 out test
Thread-1 in test
Thread-1 out test
Thread-2 in test
Thread-2 out test
Thread-3 in test
Thread-3 out test
Thread-4 in test
Thread-4 out test

我们可以看到线程都是按顺序执行的,它和synchronized的作用一样,但是它更加的强大,下面我们来慢慢了解。


Condition

在前面的的文章中,我们知道synchronized,wait(),notify()和notifyAll()方法结合使用可以实现线程同步以及通信的功能,然而ReentrantLock和Condition一起使用同样可以实现上面所说的功能,下面我们来看看代码:

public class LockTool {

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void test() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis());
            condition.await();
            lock.unlock();
            System.out.println(Thread.currentThread().getName() + " " + System.currentTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void test2() {
        lock.lock();
        condition.signal();
        lock.unlock();
    }
}

public class lockmain {

    public static void main(String[] args) {
        try {
            LockTool tool = new LockTool();
            ThreadA threadA = new ThreadA(tool);
            threadA.start();
            Thread.sleep(3000);
            tool.test2();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }
}

结果为:

Thread-0 1566178593185
Thread-0 1566178596190

看结果我们发现线程在调用await方法过后处于阻塞状态,直到我们调用signal方法后,线程才继续执行,这里和wait(),notify()方法很相似。


公平锁和非公平锁

ReentrantLock在使用的时候也可以分为公平锁和非公平锁,公平锁的意思是线程在获取锁顺序是按照线程加锁的顺序,先加锁的线程就会现获取锁。而非公平锁的意思是线程获取锁的顺序是随机的,和线程加锁的顺序并没有关系,这样就有可能造成一些线程一直无法获取锁,这就是非公平锁。下面我们通过代码来看看:

public class LockTool {

    //这里的true为公平锁
    private ReentrantLock lock = new ReentrantLock(true);

    public void test() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "获取锁");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class lockmain {

    public static void main(String[] args) {
        LockTool lockTool = new LockTool();
        List<ThreadA> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new ThreadA(lockTool));
        }

        for (int i = 0; i < 10; i++) {
            list.get(i).start();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "运行");
            lockTool.test();
        }
    }
}

结果为:

Thread-0运行
Thread-0获取锁
Thread-1运行
Thread-1获取锁
Thread-2运行
Thread-2获取锁
Thread-3运行
Thread-3获取锁
Thread-4运行
Thread-4获取锁
Thread-5运行
Thread-5获取锁
Thread-6运行
Thread-7运行
Thread-6获取锁
Thread-7获取锁
Thread-8运行
Thread-8获取锁
Thread-9运行
Thread-9获取锁

线程的执行顺序是有序。
我们将公平锁修改为非公平锁,在看看代码:

    private ReentrantLock lock = new ReentrantLock(false);

结果为:

Thread-0运行
Thread-2运行
Thread-0获取锁
Thread-3运行
Thread-3获取锁
Thread-1运行
Thread-2获取锁
Thread-4运行
Thread-4获取锁
Thread-1获取锁
......

当设置成非公平锁的时候,就有可能出现随机获取锁的情况。


getHoldCount()

getHoldCount()方法意思是获取当前线程保持此锁锁定的个数,下面我们用代码来演示一下:

public class LockTool {

    //这里的true为公平锁
    private ReentrantLock lock = new ReentrantLock();

    public void test1() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "获取锁1 总共获取锁个数为:" + lock.getHoldCount());
            test2();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private void test2() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "获取锁2 总共获取锁个数为:" + lock.getHoldCount());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class lockmain {

    public static void main(String[] args) {
        LockTool tool = new LockTool();
        ThreadA threadA = new ThreadA(tool);
        threadA.start();
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "运行");
            lockTool.test1();
        }
    }
}

结果为:

Thread-0运行
Thread-0获取锁1 总共获取锁个数为:1
Thread-0获取锁2 总共获取锁个数为:2

getQueueLength()

getQueueLength()方法是获取正在等在次锁的线程个数,下面看一个例子:

public class LockTool {

    public ReentrantLock lock = new ReentrantLock();

    public void test() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "获取锁");
            Thread.sleep(10000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class lockmain {

    public static void main(String[] args) {
        try {
            LockTool tool = new LockTool();
            for (int i = 0; i < 5; i++) {
                ThreadA threadA = new ThreadA(tool);
                threadA.start();
            }
            Thread.sleep(2000);
            System.out.println("等待线程个数为:" + tool.lock.getQueueLength());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "运行");
            lockTool.test();
        }
    }
}

结果为:

Thread-0运行
Thread-0获取锁
Thread-1运行
Thread-2运行
Thread-3运行
Thread-4运行
等待线程个数为:4

我们可以看到5个线程,1个获取了锁,等待此锁的就是4个线程。


getWaitQueueLength()

getWaitQueueLength()方法的作用是获取同一个Condition调用了await方法,并且正在阻塞的线程个数,下面我们来看看代码:

public class LockTool {

    public ReentrantLock lock = new ReentrantLock();
    public Condition condition = lock.newCondition();

    public void test() {
        try {
            lock.lock();
            condition.await();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void show() {
        lock.lock();
        System.out.println("同一个condition等待线程为:" +
                lock.getWaitQueueLength(condition));
        lock.unlock();
    }
}

public class lockmain {

    public static void main(String[] args) {
        try {
            LockTool tool = new LockTool();
            for (int i = 0; i < 6; i++) {
                ThreadA threadA = new ThreadA(tool);
                threadA.start();
            }
            Thread.sleep(2000);
            tool.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }
}

结果为:

同一个condition等待线程为:6

hasQueueThread()/hasQueueThreads()

hasQueueThread()意思是查询当前线程是否在等待此锁,hasQueueThreads()意思是查询是否有线程在等待此锁,下面我们看看代码:

public class LockTool {

    public ReentrantLock lock = new ReentrantLock();

    public void test() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "获取锁");
            Thread.sleep(10000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void show(Thread thread) {
        System.out.println(thread.getName() + "是否等待:" + lock.hasQueuedThread(thread));
        System.out.println("是否有线程等待:" + lock.hasQueuedThreads());
    }
}

public class lockmain {

    public static void main(String[] args) {
        try {
            LockTool tool = new LockTool();
            ThreadA threadA = new ThreadA(tool);
            threadA.setName("A");
            ThreadB threadB = new ThreadB(tool);
            threadB.setName("B");
            threadA.start();
            threadB.start();
            Thread.sleep(2000);
            tool.show(threadB);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }

    public static class ThreadB extends Thread {

        private LockTool lockTool;

        public ThreadB(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }
}

结果为:

A获取锁
B是否等待:true
是否有线程等待:true

hasWaiters()

hasWaiters()方法是获取是否有线程正在等待有相同Condition的线程释放阻塞,下面我们看看代码:

public class LockTool {

    public ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void test() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "获取锁");
            condition.await();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        System.out.println(Thread.currentThread().getName() + "完成");
    }

    public void show() {
        lock.lock();
        System.out.println("是否有线程正在等待:" + lock.hasWaiters(condition));
        lock.unlock();
    }
}

public class lockmain {

    public static void main(String[] args) {
        try {
            LockTool tool = new LockTool();
            ThreadA threadA = new ThreadA(tool);
            threadA.setName("A");
            ThreadB threadB = new ThreadB(tool);
            threadB.setName("B");
            threadA.start();
            threadB.start();
            Thread.sleep(2000);
            tool.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }

    public static class ThreadB extends Thread {

        private LockTool lockTool;

        public ThreadB(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }
}

结果为:

A获取锁
B获取锁
是否有线程正在等待:true

isHeldByCurrentThread()

isHeldByCurrentThread()意思是查询当前线程是否保持锁定,下面我们来看看代码:

public class LockTool {

    public ReentrantLock lock = new ReentrantLock();

    public void test() {
        try {
            System.out.println("是否获取锁:" + lock.isHeldByCurrentThread());
            lock.lock();
            System.out.println("是否获取锁:" + lock.isHeldByCurrentThread());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        System.out.println(Thread.currentThread().getName() + "完成");
    }
}

public class lockmain {

    public static void main(String[] args) {
        try {
            LockTool tool = new LockTool();
            ThreadA threadA = new ThreadA(tool);
            threadA.setName("A");
            threadA.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }
}

结果为:

是否获取锁:false
是否获取锁:true
A完成

isLocked()

isLocked()方法是查询此锁是否有线程保持,下面我们来看看代码:

public class LockTool {

    public ReentrantLock lock = new ReentrantLock();

    public void test() {
        try {
            System.out.println("是否获取锁:" + lock.isLocked());
            lock.lock();
            System.out.println("是否获取锁:" + lock.isLocked());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        System.out.println(Thread.currentThread().getName() + "完成");
    }
}

public class lockmain {

    public static void main(String[] args) {
        try {
            LockTool tool = new LockTool();
            ThreadA threadA = new ThreadA(tool);
            threadA.setName("A");
            threadA.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }
}

结果为:

是否获取锁:false
是否获取锁:true
A完成

ReentrantReadWriteLock

在我们使用ReentrantLock的时候,每个锁之间是互斥的,这样的好处就是可以保证线程安全,但是在保证线程安全的同时,也会降低效率。Java给我们提供了ReentrantReadWriteLock类,可以让我们同时读取数据,这样可以提升代码的效率。

读写锁分为共享锁和排它锁,读操作就是共享锁,写操作就是排它锁。读和读之间不会互斥,读和写还有写和写之间是相互排斥的。

下面我看先来看看读和读之间是怎么使用的:

public class LockTool {

    public ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void test() {
        try {
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + "进入了锁:" + System.currentTimeMillis());
            Thread.sleep(10000);
            System.out.println(Thread.currentThread().getName() + "睡眠完毕");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        System.out.println(Thread.currentThread().getName() + "完成");
    }
}

public class lockmain {

    public static void main(String[] args) {
        LockTool tool = new LockTool();
        for (int i = 0; i < 5; i++) {
            ThreadA threadA = new ThreadA(tool);
            threadA.start();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test();
        }
    }
}

结果为:

Thread-0进入了锁:1566190832212
Thread-1进入了锁:1566190832212
Thread-2进入了锁:1566190832212
Thread-3进入了锁:1566190832212
Thread-4进入了锁:1566190832213

我们可以看见虽然都加了锁,但是5个线程全部都进入了锁,证明读和读之间是不互斥的。

然后我们看看读和写之间是否互斥:

public class LockTool {

    public ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void test1() {
        try {
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + "读 进入了锁:" + System.currentTimeMillis());
            Thread.sleep(10000);
            System.out.println(Thread.currentThread().getName() + "读 睡眠完毕");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        System.out.println(Thread.currentThread().getName() + "完成");
    }

    public void test2() {
        try {
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + "写 进入了锁:" + System.currentTimeMillis());
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName() + "写 睡眠完毕");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
        System.out.println(Thread.currentThread().getName() + "完成");
    }
}

public class lockmain {

    public static void main(String[] args) {
        LockTool tool = new LockTool();
        ThreadB threadB = new ThreadB(tool);
        threadB.start();
        for (int i = 0; i < 5; i++) {
            ThreadA threadA = new ThreadA(tool);
            threadA.start();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test1();
        }
    }

    public static class ThreadB extends Thread {

        private LockTool lockTool;

        public ThreadB(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test2();
        }
    }
}

结果为:

Thread-0写 进入了锁:1566191059484
Thread-0写 睡眠完毕
Thread-0完成
Thread-1读 进入了锁:1566191064488
Thread-2读 进入了锁:1566191064488
Thread-3读 进入了锁:1566191064489
Thread-4读 进入了锁:1566191064489
Thread-5读 进入了锁:1566191064489

我们可以看到所有的读线程是在写线程完成过后才开始获取锁的,证明读和写是互斥的。

我们写下来看看写和写是是否也是互斥的,下面我们看看代码:

public class LockTool {

    public ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void test1() {
        try {
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + "读 进入了锁:" + System.currentTimeMillis());
            Thread.sleep(10000);
            System.out.println(Thread.currentThread().getName() + "读 睡眠完毕");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
        System.out.println(Thread.currentThread().getName() + "完成");
    }
}

public class lockmain {

    public static void main(String[] args) {
        LockTool tool = new LockTool();
        for (int i = 0; i < 4; i++) {
            ThreadA threadA = new ThreadA(tool);
            threadA.start();
        }
    }

    public static class ThreadA extends Thread {

        private LockTool lockTool;

        public ThreadA(LockTool lockTool) {
            this.lockTool = lockTool;
        }

        @Override
        public void run() {
            lockTool.test1();
        }
    }
}

结果为:

Thread-0读 进入了锁:1566191219974
Thread-0读 睡眠完毕
Thread-0完成
Thread-1读 进入了锁:1566191229977
Thread-1读 睡眠完毕
Thread-1完成
Thread-2读 进入了锁:1566191239981
Thread-2读 睡眠完毕
Thread-2完成
Thread-3读 进入了锁:1566191249982
Thread-3读 睡眠完毕
Thread-3完成

我们可以看到每个线程都是完毕后,下一个线程才会获取锁并执行代码,这说明写和写之间同样是互斥的。


到这里有关Lock的基本使用就讲完了,上文中如果有错误的地方欢迎大家指出。

3Q

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,711评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,079评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,194评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,089评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,197评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,306评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,338评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,119评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,541评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,846评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,014评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,694评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,322评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,026评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,257评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,863评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,895评论 2 351

推荐阅读更多精彩内容