---
title: "可重入锁／不可重入锁"
author: "fairy_xzc"
date: "2019-08-16T23:05:40Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2019-08-17T00:32:37Z"
id: 2443634
url: "https://agilestyle.iteye.com/blog/2443634"
---

**原创转载请注明出处：[https://agilestyle.iteye.com/blog/2443634](/blog/2443634)**

 

## 可重入锁

可重入锁指的是可重复可递归调用的锁，在外层使用锁之后，在内层仍然可以使用，并且不发生死锁（前提是同一个对象或者类）

Note：

**ReentrantLock和synchronized都是可重入锁**

```
public class TestLock {
    public synchronized void test1() throws InterruptedException {
        Thread.sleep(1000);
        System.out.println("test1 invoked...");
        test2();
    }

    public synchronized void test2() throws InterruptedException {
        Thread.sleep(1000);
        System.out.println("test2 invoked...");
    }

    public static void main(String[] args) throws InterruptedException {
        TestLock testLock = new TestLock();
        testLock.test1();
    }
}
```

上面的代码就是一个可重入锁的一个特点，如果不是可重入锁的话，test2可能不会被当前线程执行，可能造成死锁。 

 

## 不可重入锁

不可重入锁，与可重入锁相反，不可递归调用，递归调用就会发生死锁。

使用自旋锁来模拟一个不可重入锁

```
import java.util.concurrent.atomic.AtomicReference;

public class UnreentrantLockTest {
    private static UnreentrantLock lock = new UnreentrantLock();

    public static void main(String[] args) {
        lock.lock();

        test();

        lock.unlock();
    }

    private static void test() {
        lock.lock();

        System.out.println("test invoked...");

        lock.unlock();
    }

    private static class UnreentrantLock {
        private AtomicReference<Thread> owner = new AtomicReference<>();

        public void lock() {
            Thread currentThread = Thread.currentThread();

            for (; ; ) {
                System.out.println(owner);
                if (owner.compareAndSet(null, currentThread)) {
                    System.out.println(currentThread + " locked...");
                    return;
                }
            }
        }

        public void unlock() {
            Thread currentThread = Thread.currentThread();

            owner.compareAndSet(currentThread, null);

            System.out.println(currentThread + " unlock...");
        }
    }
}
```

Note:

使用原子引用来存放线程，同一个线程两次调用lock()方法，如果不执行unlock()释放锁的话，第二次调用自旋的时候就会产生死锁，这个锁是不可重入的

 

修改上述代码，将它改造成可重入锁，在执行每次操作之前，判断当前锁持有者是否是当前对象，采用state计数

```
import java.util.concurrent.atomic.AtomicReference;

public class ReentrantLockTest {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        lock.lock();

        test();

        lock.unlock();
    }

    private static void test() {
        lock.lock();

        System.out.println("test invoked...");

        test1();

        lock.unlock();
    }

    private static void test1() {
        lock.lock();

        System.out.println("test2 invoked...");

        lock.unlock();
    }

    private static class ReentrantLock {
        private AtomicReference<Thread> owner = new AtomicReference<>();
        private int state = 0;

        public void lock() {
            Thread currentThread = Thread.currentThread();

            if (currentThread == owner.get()) {
                state++;
                return;
            }

            for (; ; ) {
                System.out.println(owner);
                if (!owner.compareAndSet(null, currentThread)) {
                    return;
                }
            }
        }

        public void unlock() {
            Thread currentThread = Thread.currentThread();

            if (currentThread == owner.get()) {
                if (state != 0) {
                    state--;
                } else {
                    owner.compareAndSet(currentThread, null);
                }
            }
        }
    }
}
```