简单聊聊 Java ReentrantLock

2019-08-19  本文已影响0人  Jevely

大家好,这次我们来聊聊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

上一篇下一篇

猜你喜欢

热点阅读