ReentrantReadWriteLock 写锁未释放也能获取到读锁?

Reed
  • 44
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description:
 * @Author: reed
 */
public class ReadWriteLockDemo {

    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static Lock writeLock = lock.writeLock();
    private static Lock readLock = lock.readLock();
    private static int[] arr = new int[10];

    public static void main(String[] args) {
        Thread t1 = new Thread(new WriteTask());
        Thread t2 = new Thread(new ReadTask());
        Thread t3 = new Thread(new ReadTask());

        t1.start();
        t2.start();
        t3.start();
    }

    static class WriteTask implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                writeLock.lock();
                try {
                    int index = (int) (Math.random() * 10);
                    arr[index] = (int) (Math.random() * 100);
                    System.out.println("+持有写锁, 将 arr[" + index + "] 修改为 " + arr[index] + ", " + Thread.currentThread()
                            .getName());
                } finally {
                    writeLock.unlock();
                    System.out.println("-写锁释放" + ", " + Thread.currentThread()
                            .getName());
                }
            }
        }
    }

    static class ReadTask implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                readLock.lock();
                try {
                    int index = (int) (Math.random() * 10);
                    System.out.println("+持有读锁,下标 " + index + ",值 " + arr[index] + ", " + Thread.currentThread()
                            .getName());
                } finally {
                    readLock.unlock();
                    System.out.println("-读锁释放" + ", " + Thread.currentThread()
                            .getName());
                }
            }
        }
    }
}

其中一次运行结果:

image.png

写锁(Thread-0)还没释放前为什么能获取到读锁吗?获取读锁的线程(Thread-2, 与持有写锁的线程不同)不应该是阻塞的吗?

image.png

回复
阅读 633
1 个回答
✓ 已被采纳

你的想法是没错的。
执行的语句可能是这样的:
0线程持有写锁
0线程释放写锁
1线程获取读锁
1线程获取读锁
2线程获取读锁
2线程获取读锁
(12获取释放的打印略过)
0线程打印释放写锁
也就是说,读锁执行完writeLock.unlock();,读线程就可以获取锁,此时写线程还没执行打印语句,就造成了上面的运行情况

你知道吗?

宣传栏