多线程-读写锁模式

34 篇文章 13 订阅
7 篇文章 0 订阅

文章目录

1. 读写锁模式

/**
 * 读写锁
 * 1. 写写加锁
 * 2. 读写加锁
 * 3. 写都加锁
 * 4. 读读不加锁
 * 
 */
public class ReadWriteLock {

    private int readingReaders = 0; // 正在读线程数
    private int waitingReaders = 0; // 正在等待的读线程
    private int writingWriters = 0; // 正在写的线程
    private int waitingWriters = 0;  // 等待写的线程数

    public synchronized void readLock() throws InterruptedException {
        this.waitingReaders++; // 获取到锁, 说明可以加入等待读队列.
        try {
            while (this.writingWriters > 0) { // 若存在正在写的线程, 得等待写完成.
                this.wait();
            }

            this.readingReaders++; // 因为使用了while, 所以, 当while结束的时候, 说明写完成了. 可以读取数据了.
        } finally {
            this.waitingReaders--; // 因为已经多了一个正在读的线程, 说明等待读的线程应该-1
        }
    }

    public synchronized void readUnLock() {
        this.readingReaders--; //释放正在读线程
        this.notifyAll(); //唤醒其它等待的线程
    }

    public synchronized void writeLock() throws InterruptedException {
        this.waitingWriters++; // 获取到锁, 说明可以加入等待写队列.
        try {
            // 若有线程在写, 或者有线程在读, 都需要等待, 不可以写.
            while (this.waitingWriters > 0 || this.readingReaders > 0) {
                this.wait();
            }

            // 因为使用了while, 所以, 当while结束的时候, 说明写/读完成了. 可以写取数据了.
            this.writingWriters++;
        } finally {
            this.waitingWriters--; // 因为已经多了一个正在写的线程, 说明等待写的线程应该-1
        }
    }

    public synchronized void writeUnLock() {
        this.writingWriters--; //释放写线程
        this.notifyAll(); // 唤醒其它正在等待的线程
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值