ReadWriteLock读写锁

admin
2022-03-19 / 0 评论 / 124 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年03月19日,已超过852天没有更新,若内容或图片失效,请留言反馈。

读写锁

package com.yanxizhu;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @description: 读写锁(互斥锁)
 * @author: <a href="mailto:batis@foxmail.com">清风</a>
 * @date: 2022/3/19 15:23
 * @version: 1.0
 */
public class ReadWriteDemo {
    public static void main(String[] args) {
        ReadWriteTest readWriteTest = new ReadWriteTest();

        new Thread(()->{
            readWriteTest.write((int) (Math.random()*101));
        },"写锁").start();

        for(int i=1;i<50;i++){
            new Thread(()->{
                readWriteTest.get();
            },"读锁").start();
        }

    }
}

class ReadWriteTest{
    int num =0;

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    //读
    public void get(){
        readWriteLock.readLock().lock();
        try{
            System.out.println(num+"=="+Thread.currentThread().getName());
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

    //写
    public void write(int i){
        readWriteLock.writeLock().lock();
        try{
            this.num=i;
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }
}
5

评论 (0)

取消