原创

ReadWriteLock读写锁的使用

读写锁:

写写、读写 是互斥的

读读是不需要互斥的

如下示例代码中,可以看到读的操作,一部分是在写操作之前,一部分是在写操作之后,说明读是不互斥的。写是

file

示例代码:

package com.debuggg.test1.main2;

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

/**
 * 作者 ZYL
 * 功能描述 : ReadWriteLock: 读写锁
 *  写写/读写 需要“互斥”
 *  读读 不需要互斥
 * 日期 2020-03-30 12:34
 * 参数 null
 * 返回值
 */
public class TestReadWriteLock {
    public static void main(String[] args) {
        ReadWriteLockDemo lockDemo = new ReadWriteLockDemo();

        new Thread(() -> lockDemo.set(18) ,"write: ---------------------- ").start();

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                lockDemo.get();
            },"read" + (i +1)).start();
        }
    }
}

class ReadWriteLockDemo{
    private int number = 0;

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    //读操作
    public void get(){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ":" + number);
        }finally {
            lock.readLock().unlock();
        }
    }

    //写操作
    public void set(int number){
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName());
            this.number = number;
        }finally {
            lock.writeLock().unlock();
        }
    }
}
正文到此结束
本文目录