公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。

为了提高性能,java提供了读写锁,

读锁: 在读的地方使用读锁,可以多个线程同时读。

写锁: 在写的地方使用写锁,只要有一个线程在写,其他线程就必须等待

例子:

public static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public static Lock readLock = readWriteLock.readLock();
public static Lock writeLock = readWriteLock.writeLock();

public static void readWriteLock(){

    Thread t1 = new Thread(() -> {

        for (int i = 0; i < 10; i++) {
            try {
                readLock.lock();
                System.out.println("T1 Read!");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                System.out.println("T1 unLock!");
                readLock.unlock();
            }
        }
    });

    Thread t2 = new Thread(() -> {
        for (int i = 0; i < 10; i++) {
            try {
                readLock.lock();
                System.out.println("T2 Read!");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                System.out.println("T2 unLock!");
                readLock.unlock();
            }
        }
    });

    Thread t3 = new Thread(() -> {

        for (int i = 0; i < 5; i++) {
            try {
                writeLock.lock();
                System.out.println("T3 write!");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                System.out.println("T3 unLock!");
                writeLock.unlock();
            }
        }
    });

    t1.start();
    t2.start();
    t3.start();
}
posted on 2021-08-09 17:05  公众号/架构师与哈苏  阅读(45)  评论(0编辑  收藏  举报